Entity Framework: A referential integrity constraint violation on many to many relationship

后端 未结 6 1276
一向
一向 2020-12-15 15:27

Hey I have an application with a bunch of inproc caching and entity framework. When I want to write an update to an entity I reattach the cached copy. I track all things I\'

6条回答
  •  遥遥无期
    2020-12-15 16:25

    I just had this problem and came up with a pretty quick solution. My issue was with a many-many table.

    Public class Pictures_Tag
    {
        [Key]
        [Column(Order = 0)]
        [ForeignKey("Picture")]
        public Int16 Picture_ID { get; set; }
        [Key]
        [Column(Order = 1)]
        [ForeignKey("ImageTag")]
        public Int16 ImageTag_ID { get; set; }
        public virtual Picture Picture { get; set; }
        public virtual ImageTag ImageTag { get; set; }
    }
    

    I added the line where I assigned Picture = db.Pictures... and then it worked fine (not exactly sure why)

    [HttpPost]
    public ActionResult Edit2(WebSiteEF2017C.Models.Pictures_Tag p)
    {     
        using (var db = new thisModel(Session["org"].ToString())
        {
             p.Picture = db.Pictures.Where(z => z.ID == p.Picture_ID).FirstOrDefault();
             db.Pictures_Tags.Attach(p);
             db.Entry(p).State = EntityState.Modified;
             db.SaveChanges();
             return View(db.Pictures_Tags.Include(x => x.Picture)
                        .Where(n => n.Picture_ID == p.Picture_ID & n.ImageTag_ID == p.ImageTag_ID).FirstOrDefault());
        }
    }
    

提交回复
热议问题