简体   繁体   中英

Enforce Entity Framework to follow constraints defined in database

I have a table with 10 columns, in which 7 of them are not null with constraints on it.

ALTER TABLE [dbo].[MyTable] 
    ADD DEFAULT (1) FOR [Column1]

Now, when I am inserting 3 columns from Entity Framework like below, it is not inserting the default values into the table:

Table obj1 = new Table();
obj1.Column7 = someValue;
obj1.column8 = someValue;
obj1.column9 = someValue;
context.Entry(obj1).State = EntityState.Added;
context.SaveChanges(); 

Unlike my expectation, above statement is just updating 3 columns and not using the default values for the other 7 columns.

How can I enforce Entity Framework to insert default values defined by the constraint in database?

The default values as defined in your SQL Server table structure are only applied if you have an INSERT statement that leaves out those columns - eg doesn't provide any value (including NULL ) for those columns.

EF however will always supply values for all columns as defined by the entity - eg it will supply NULL for any values not explicitly set. There's nothing you can do about this, as far as I know.

There are some workarounds:

  • you could create a stored procedure which would take only those values you want to supply, and would run a SQL INSERT statement that would leave out the columns with default values, eg

    INSERT INTO dbo.MyTable (colA, colB, ..., colZ) -- *exclude* "Column1" here! VALUES ( .........)

    With this, SQL Server would then use the configured default values for those column that have one defined and which are not mentioned in the column list of the INSERT INTO statement

  • you could probably do something similar on the EF level, by specifying a second class, that would be almost identical to your current entity class - but that would leave out the columns you want to have set by SQL Server's configured default values. If you save this "slimmed down" entity, EF would create a SQL statement that would include only those columns that it knows about (in terms of the fields of that slimmed down class) and this would result basically in the same as above - an INSERT INTO statement that excludes those columns which are automatically set by a configured SQL Server default constraint

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM