实体框架6更新多对多不更新或加载子

本文关键字:更新 加载 框架 实体 | 更新日期: 2023-09-27 18:18:30

我想更新一个与其他记录有多对多关系的记录。我的问题是,它总是试图也更新它的孩子,这失败了,因为孩子有必需的字段,我只提供ID。

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

Address有一个IEnumerable,其中包含productid,其他字段为空或具有默认值(int和bool)。

我得到以下错误:

Property: Name Error: Please enter a Name Property: Description错误:请输入描述属性:类别错误:请输入类别

[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它只应该插入地址和更新关系表。我不想通过首先加载产品来生成开销。我也不喜欢在没有必要的时候访问Products表。

实体框架6更新多对多不更新或加载子

你应该使用:

  • 附加方法(DbSet)来激活修改跟踪。

Attach用于用已知的实体重新填充上下文已经存在于数据库

  • 条目方法(DbContext),用于设置附加实体的状态。

您可能还想阅读添加/附加和实体状态

对于许多产品:

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