Disabling Entity Framework's default value generation (Code First)

≡放荡痞女 提交于 2020-01-01 04:45:12

问题


I have a column in the database that cannot be null, and I want to set it to have a default value in the database . The problem is that entity framework seems to create a default value itself (for example, int => 0), and completely ignores the default value constraint in the database.

Is there any way to disable this default valuing of entity framework?


回答1:


Natively, Entity framework do not allows this. You have to do some code to it. This answer from another site seems to had solved the problem for many people.

He "hacks" it (as he told) by doing something like that:

public partial class YourEntityClass {
     public YourEntityClass() {
         this.PropertyNameWithDefaultValue = default(int);
     }
}

Note 1 : Someone mention that it may not work in EF4

Personal note : Sorry for my english, I usually speak French.




回答2:


I have found that you can decorate your fields with the following attribute.

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]



回答3:


Sometimes we need to do manually what EF doesn't do automatically for us.

In case using EF 4.1 "Code First", I usually create a separated class DbInitializer derived from IDatabaseInitializer, and in the implementation of the InitializeDatabase method, just call the

context.Database.ExecuteSqlCommand("ALTER TABLE TABLENAME ... ");

Now at the static constructor of the class derived from DbContext, just call the initializer:

Database.SetInitializer(new DbInitializer());

In this way, it's possible to specify any database DML/DDL commands to alter tables/columns just to make sure the DB is like we want.




回答4:


"Computed" fields in EF are not the same as fields with default values in SQL. A computed field is one that is computed on the server and shouldn't be altered when an object is submitted. If you put a Computed tag on a field, you will get the default when you first create the object, but then you will not be able to change that field later on. So, if you get an entity from the DB make a change to a computed field and then call "saveChanges()" on your entity context, the field will not be altered in the DB.

Better to use EF defaults by setting the Default Value for the attribute in the EDMX editor.

It's a pain in the butt that the EDMX updater can't read the field defaults when there is a one to one mapping between the entity field and the database field.




回答5:


You can update the EDMX model to change the default value for any column via the Properties window. However, Entity Framework doesn't seem to pickup DEFAULT constraints automatically. Not sure if there is a way to make it do that.



来源:https://stackoverflow.com/questions/6846952/disabling-entity-frameworks-default-value-generation-code-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!