Insert problem

May 23, 2012 at 6:13 AM

context.Insert("Book", item).Execute();

When I do it like this, it will cause an exception. 'XXX has not a default value.'

It forces me to invole automap or column method.

But my Id is not auto-increment, so i just want to insert everything into db.

How could I do?

Coordinator
May 23, 2012 at 7:57 AM

The insert builder supports manual mapping and auto mapping.

The manual mapping approach is basically an include approach where you define what columns you would like to include in the insert query:
context.Insert("Book", item).Column(x => x.CategoryId).Column(x => x.Name).Execute(); 

While the auto mapping will automatically include all the columns into the insert query:
context.Insert("Book", item).AutoMap().Execute();

or all the columns except one or more:
context.Insert("Book", item).AutoMap(x => x.CategoryId).Execute();

The reasons for supporting these approaches is that one might have slightly different business models and needs. For instance the auto mapping approach with or without excludes is perfect to use in a project with few developers where the developers have 100% track of the source code. Because if you add a new property to your .NET entity class and you forget or do not want this property to be part of your insert query then you need to remember to add an exclude otherwise the insert query will fail (if the new property do not have a matching column in the database).
However for the manual approach, if you have a many developers and few integration tests, then explicitly defining all the columns to be part of the insert query is safer since the insert query will be unaffected and will not fail when you add a new property that do not have a matching column in the database.

Calling AutoMap whenever you want to auto map is one extra operations but it gives you much more flexibility.

So the answer: context.Insert("Book", item).AutoMap().Execute();

May 23, 2012 at 8:56 AM

 

context.Insert("Book", item).AutoMap().Execute();

It works! Thank you!