2015-10-19 60 views
2

我想更新与其他记录具有多对多关系的记录。 我的问题是,它总是试图更新其子项,由于该子项具有必填字段而我只提供该ID,所以失败。实体框架6多对多更新而不更新或加载孩子

我不想加载子对象。我只是想要它插入地址并更新多对多表。

地址具有一个IEnumerable,它包含ProductID,其他字段为空或具有默认值(ints和bools)。

我收到以下错误:

Property: Name Error: Please enter a Name Property: Description Error: Please enter a Description Property: Category Error: Please enter a Category

[HttpPost] 
    public ActionResult ReceiveOrder(Address address) 
    { 
     EFDbContext context = new EFDbContext(); 

      context.Addresses.Add(address); 
      context.SaveChanges(); 
      context.Dispose(); 
      return Json(new { success = true, responseText = "Okay" }, JsonRequestBehavior.AllowGet); 
    } 

Address类:

public class Address 
{ 
    public int AddressID { get; set; } 
    public string Name { get; set; } 
    public string Street { get; set; } 
    public virtual List<Product> Products { get; set; } 
    public bool Giftwrap { get; set; } 
} 

产品类

public class Product 
{ 

    [HiddenInput(DisplayValue =false)] 
    public int ProductID { get; set; } 
    [Required(ErrorMessage ="Please enter a Name")] 
    public string Name { get; set; } 
    [DataType(DataType.MultilineText)] 
    [Required(ErrorMessage = "Please enter a Description")] 
    public string Description { get; set; } 
    [Required(ErrorMessage = "Please enter a Price")] 
    public decimal Price { get; set; } 
    [Required(ErrorMessage = "Please enter a Category")] 
    public string Category { get; set; } 

    public byte[] ImageData { get; set; } 
    public string ImageMimeType { get; set; } 

    public virtual List<Address> Addresses { get; set; } 
} 

我怎么告诉EF其只应该插入解决并更新关系T能够。我不想通过首先加载产品来生成开销。如果没有必要,我也不喜欢访问产品表。

+0

你有懒加载关闭 – bilpor

+0

我试图把'context.Configuration.LazyLoadingEnabled = FALSE;在'那里,但没有效果 – Kendoha

+0

我想知道是不是因为你没有规范化表格。通常在多对多的关系中,你会有一个链接表。我想如果你引入链接表,那么这可能会解决这个问题。另一件事是,一般情况下,如果您将延迟加载设置为false,那么从类中删除关键字virtual有时会导致这些问题。 – bilpor

回答

1

你应该使用:

  • Attach方法(DbSet)激活修改跟踪。

Attach is used to repopulate a context with an entity that is known to already exist in the database

  • Entry方法(的DbContext),以能够设置所连接的实体的状态。

您可能ALSA想读Add/Attach and Entity States

许多产品:

public ActionResult ReceiveOrder(Address address) 
{ 
    EFDbContext context = new EFDbContext(); 

    context.Set<Addresses>().Attach(address); 
    foreach(Product p in address.Products) { 
     context.Set<Products>().Attach(p); 
    } 
    context.Entry(address).State = EntityState.Added; 

    context.SaveChanges(); 
    context.Dispose(); 
    return Json(new { success = true, responseText = "Okay" }, 
      JsonRequestBehavior.AllowGet); 
} 
+0

既没有寻址Single()方法也没有上下文使用Attach()方法。我不清楚你想要做什么。它似乎也只是试图附加一个产品,是不是必须在foreach循环中进行?你正在清除'address.Products',是不是没有删除所有关系? – Kendoha

+0

如果您有多个产品,则确实必须使用循环进行附加,然后添加。在这种情况下,你可以附加每个实体的地址集作为地址添加 – tschmit007

+0

非常感谢你,像一个魅力和死SQL语句看起来很干净。正是我想要的。最后一个问题:这种方法会删除这两个对象之间已经存在的引用,还是只是添加新引用? – Kendoha