0
votes

This is a follow up to this question
Entity Framework 4 not respecting database constraints for numeric fields

Is it possible to achieve the following

Table: Foo
PkId - int, primary, autoincrement
Bar - int, allow null=false, no default

Now when generating the EF model from the database the 'Bar' field is correctly defined as Nullable=false, Type=Int32.

Now when I do the following

var foo = new Foo();
context.AddToFoos(foo);
context.SaveChanges();

The row is inserted into the database and 'Bar' has a value of 0?

What I would expect is an application level exception because Bar hasn't technically been set by the application. Its .Net default value does not automatically translate to a valid value for a particular database.

The behaviour should be similar to string columns in the DB. Strings are correctly handled because they have a null state and this translates well.

How is this normally achieved for numeric columns?

1

1 Answers

0
votes

Don't forget to set the value of the Bar property in your model object when you don't want to store 0. When you create a new object and call SaveChanges an INSERT command is sent to the database which contains the value of all your model properties which are mapped to the DB table. An int property in a class has always a value and you have set this value to 0 - namely by calling the object's constructor.

EF doesn't sent only one half of the object to the database, that's an essential point of an Object-Relational-Mapper. Of course by submitting a raw SQL INSERT command you can set only one half of a table row's column values and you would get an exception if you don't set a value for the Bar column. But when you use an ORM you don't submit INSERT commands but you store new objects.

What is exactly the problem? If not having a value for Bar is valid the column should be nullable and the property int?. If it must have a value but not the value 0 then it's a matter of setting Bar to 1 or something in the object's constructor or apply proper validation before you save an object.

The kind of exception you would like to have is impossible and makes no sense in my opinion because it's impossible not to set a value in the INSERT command EF will submit when storing the object