我想更新与其他记录有多对多关系的记录。 我的问题是,它总是尝试更新它的 child ,但失败了,因为 child 有必填字段,而我只提供 ID。
我不想加载子对象。我只希望它插入地址并更新多对多表。
Address 有一个 IEnumerable,其中包含 ProductID,其他字段为空或具有默认值(整数和 bool 值)。
我收到以下错误:
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);
}
地址类:
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 它只应该插入地址并更新关系表。我不想通过先加载产品来产生开销。我也不喜欢在不必要时访问 Products 表。
最佳答案
你应该使用:
- Attach方法 (DbSet) 激活修改跟踪。
Attach is used to repopulate a context with an entity that is known to already exist in the database
- Entry方法 (DbContext) 能够设置附加实体的状态。
您可能还想阅读 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);
}
关于c# - Entity Framework 6 更新多对多而不更新或加载 Child,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33213088/