实体框架4不遵守数字字段的数据库约束 [英] Entity Framework 4 not respecting database constraints for numeric fields

查看:171
本文介绍了实体框架4不遵守数字字段的数据库约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,我在DB中有一个表定义如下



表:Foo

PkId - int,primary,autoincrement

Bar - int,allow null = false,no default



现在,从数据库生成EF模型时,'Bar'字段被正确定义为Nullable =现在,当我执行以下操作时:

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

该行被插入到数据库中,Bar的值为0?我会期待一个例外,因为Bar尚未设置。我意识到0不是null,但也不是我设置的值。



这是设计还是我误解了某些东西?

解决方案

它不可空,因此是一个int。 int的默认值为0.所以DB很高兴,框架也很好。


Say, I have a table in the DB defined as follows

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? I would have expected an exception because Bar hasn't been set. I realise that 0 isn't null but its also not a value that I've set.

Is this by design or have I misunderstood something?

解决方案

It's not nullable and thus an int. The default of int is 0. So the DB is happy and the framework is fine as well.

这篇关于实体框架4不遵守数字字段的数据库约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆