为什么会抛出 NULL 值异常?
由于某种原因,我在 db.SaveChanges(); 指令中收到以下错误:
Cannot insert the value NULL into column 'UserId', table 'XXXXXXXXX_Dev.dbo.Portfolios'; column does not allow nulls. INSERT fails.
The statement has been terminated.
控制器代码:
[HttpPost]
[Authorize]
public ActionResult Create(Portfolio portfolio)
{
if (ModelState.IsValid)
{
portfolio.UserId = (Guid)Membership.GetUser().ProviderUserKey;
db.AddToPortfolios(portfolio);
db.SaveChanges();
}
return View("MyPortfolios");
}
我已单步执行调试器并确认正在填充 UserID。
更新:
我尝试将 db.AddToPortfolios(portfolio); 更改为 db.Portfolios.AddObject(portfolio); 但仍然存在同样的问题。
Portfolios
是一个 ObjectSet
,我应该使用 Attach()
方法吗?
For some reason I am getting the following error at the db.SaveChanges();
instruction:
Cannot insert the value NULL into column 'UserId', table 'XXXXXXXXX_Dev.dbo.Portfolios'; column does not allow nulls. INSERT fails.
The statement has been terminated.
Controller code:
[HttpPost]
[Authorize]
public ActionResult Create(Portfolio portfolio)
{
if (ModelState.IsValid)
{
portfolio.UserId = (Guid)Membership.GetUser().ProviderUserKey;
db.AddToPortfolios(portfolio);
db.SaveChanges();
}
return View("MyPortfolios");
}
I have stepped through the debugger and confirmed that UserID is being populated.
Update:
I have tried changing db.AddToPortfolios(portfolio);
to db.Portfolios.AddObject(portfolio);
but it is still having the same problem.
Portfolios
is an ObjectSet
, should I use the Attach()
method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我仅从一种情况知道此异常,即:
UserId
不是数据库中的标识列,但在 EF 模型中,相应的属性被标记为这样 - 这意味着它要么显式归因于 < code>DatabaseGenerateOption.Identity 或按照约定隐式地进行。问题是,在这种情况下,EF 不会将属性值发送到 Db(无论是否设置),因为它假定 DB 将完成创建列值的工作。但 Db 没有,因此是例外。
只是一个猜测。
编辑:
要解决该问题,您必须使用
DatabaseGeneratedOption.None
标记UserId
。I know this exception from only one situation, that is:
UserId
is not an identity column in your database but in the EF model the corresponding property is flagged as such - which means it is either explicitely attributed withDatabaseGeneratedOption.Identity
or implicitely by conventions.The problem is that in this case EF won't sent the property value to the Db (no matter if it's set or not) because it assumes that the DB will do the work to create a column value. But the Db doesn't, hence the exception.
Just a guess.
Edit:
To solve the problem you must flag
UserId
withDatabaseGeneratedOption.None
.