尝试使用 DbContext 使用 .Add() 方法保存时出现“无法将 NULL 值插入列”。请检查我的 POCO 和保存方法

2024-01-29

首先使用代码,所有内容似乎都可以与下面的内容分开,当我使用 ObjectContext 并调用 context.PCBuilds.AddObject(pcBuild) 之前,它也可以工作,但在切换到 DbContext 后,它给了我错误。

EFDbContext context = new EFDbContext();

        public ActionResult Index()
        {
            PCBuild pcBuild = new PCBuild();
            pcBuild.BuildID = 34245;
            pcBuild.BuildName = "Test99";
            pcBuild.MarkUp = 25;
            pcBuild.BDetails = new List<BDetail>();

            context.PCBuilds.Add(pcBuild);

            //repository.PCBuilds.Attach(pcBuild);

            context.SaveChanges();


            return View();
        }

给我:Cannot insert the value NULL into column 'BuildID', table 'C:\USERS\ADMIN\DOCUMENTS\VISUAL STUDIO 2010\PROJECTS\NEOCART\NEOCART.WEBUI\APP_DATA\NEODBX.MDF.dbo.PCBuilds'; column does not allow nulls. INSERT fails.在调用 SaveChanges 之前已明确设置 BuildID。似乎由于某种原因调用 .Add(pcBuild) 不会添加填充的对象,并且当调用 savechanges 时它会尝试插入空的 PCBuild ?

这是 POCO 的

public class PCBuild
    {
        [Key]
        public int BuildID { get; set; }

        public string BuildName { get; set; }

        public string Socket { get; set; }

        public decimal? MarkUp {get; set;}

        [InverseProperty("PCBuild")]
        public virtual ICollection<BDetail> BDetails { get; set; }



    }


public class BDetail
{
    [Key]
    public int LineID { get; set; }

    [ForeignKey("PCBuild")]
    public int BuildID { get; set; }

    [ForeignKey("Product")]
    public int ProductID { get; set; }

    public bool? IsSelected { get; set; }

    [InverseProperty("BDetails")]
    public virtual PCBuild PCBuild { get; set; }

    [InverseProperty("BDetails")]
    public virtual Product Product { get; set; }


}

Use 存储生成的属性 http://blogs.msdn.com/b/efdesign/archive/2010/03/30/data-annotations-in-the-entity-framework-and-code-first.aspx on the PCBuild.BuildID财产。它不仅是一把钥匙,而且IDENTITY field.

UPDATE Actually http://msdn.microsoft.com/en-us/data/gg193958, 它应该是[DatabaseGenerated(DatabaseGenerationOption.Identity)]注解。上面链接的文章描述了早期的 CTP 版本。

UPDATE 2等等,密钥是由应用程序生成的,它不是数据库中的身份列?将注释更改为[DatabaseGenerated(DatabaseGenerationOption.None)],重新创建上下文并重建应用程序。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

尝试使用 DbContext 使用 .Add() 方法保存时出现“无法将 NULL 值插入列”。请检查我的 POCO 和保存方法 的相关文章

随机推荐