Disabling Entity Framework's default value gen

2019-03-26 06:36发布

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?

5条回答
趁早两清
2楼-- · 2019-03-26 06:46

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.

查看更多
ら.Afraid
3楼-- · 2019-03-26 06:55

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

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
查看更多
Summer. ? 凉城
4楼-- · 2019-03-26 06:59

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.

查看更多
别忘想泡老子
5楼-- · 2019-03-26 07:04

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

查看更多
Animai°情兽
6楼-- · 2019-03-26 07:06

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.

查看更多
登录 后发表回答