c# - 为什么 EF 试图在 id 列中插入 NULL?

标签 c# .net entity-framework entity-framework-4

我正在使用 Entity Framework 4.0(模型优先)编写我的项目。在项目开始时,我遇到了这个问题:我试图将填充的对象插入到数据库中,但是我得到了一个异常:

Cannot insert the value NULL into column 'CategoryId', table 'ForumDB.dbo.Categories'; column does not allow nulls. INSERT fails. The statement has been terminated.

代码:

    Category usingCategory = new Category("Using Forums", "usingforums", 0);
    using (Context)
    {
        Context.Categories.AddObject(usingCategory);
        Context.SaveChanges();
    }

我检查了这个对象,我确定它已被填充。

以防万一:

public Category(string name, string urlName, int index)
{
    CategoryId = Guid.NewGuid();
    Name = name;
    UrlName = urlName;
    CategoryIndex = index;
}

这是怎么回事?

最佳答案

看看这个:https://stackoverflow.com/a/5338384/171703 - Entity Framework 可能假设您的 CategoryId 字段是一个身份,因此将 null 传递给数据库,期望它为您填充。

关于c# - 为什么 EF 试图在 id 列中插入 NULL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8855100/

相关文章:

c# - 以 XmlDocument 作为返回类型的 Web 方法在 asp.net core 的 SoapCore 中失败

c# - 拥有不同配置的 NLog 记录器

c# - Entity Framework ,获取子类的类型?

javascript - 在 DataTable 中使用 LINQ to list<AJAX>

c# - .NET 控制台窗口

c# - WinForms 上的单向绑定(bind)?

c# - AddIdentity 与 AddIdentityCore

.net - 如何将 'Tags' 添加到我的简单博客文章类库和存储库中?

c# - EFCore 保存具有关系 ID 的实体

c# - 何时在 Entity Framework Code First 中使用存储过程和 SQL 查询