我正在使用 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/