为什么EF尝试在id列中插入NULL? [英] Why is EF trying to insert NULL in id-column?

查看:155
本文介绍了为什么EF尝试在id列中插入NULL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在使用Entity Framework 4.0(Model First)编写我的项目。
在项目开始时,我遇到这个问题:我试图将填充的对象插入到数据库中,但我得到一个例外:



无法将值NULL插入列CategoryId,表ForumDB.dbo.Categories;列不允许为空INSERT failed。该语句已被终止。

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

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

以防万一:

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

请告诉我发生了什么?
感谢任何帮助!

解决方案

看看这个: https://stackoverflow.com/a/5338384/171703 - 实体框架可能假设您的CategoryId字段是一个身份,因此传递给数据库,期望它填写给你。


Sorry for my English.

I am writing my project using Entity Framework 4.0 (Model first). At the beginning of the project, I faced with this problem: I am trying to insert the filled object in the database, but I get an exeption:

"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();
    }

I checked this object, and I am sure that it is filled.

Just in case:

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

Please tell me what is going on? Thanks for any help!

解决方案

Have a look at this: https://stackoverflow.com/a/5338384/171703 - entity framework might be assuming that your CategoryId field is an identity and therefore passing null to the database expecting it to fill it for you.

这篇关于为什么EF尝试在id列中插入NULL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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