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

天涯浪子 提交于 2019-12-03 13:16:16
Simon Dugré

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.

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

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]

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.

"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.

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.

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