为什么会抛出 NULL 值异常?

发布于 2024-11-19 10:34:38 字数 799 浏览 7 评论 0原文

由于某种原因,我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

阿楠 2024-11-26 10:34:38

我仅从一种情况知道此异常,即: 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 with DatabaseGeneratedOption.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 with DatabaseGeneratedOption.None.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文