Entity Framework 6 更新多对多,无需更新或加载子级

问题描述 投票:0回答:2

我想更新与其他记录具有多对多关系的记录。 我的问题是,它总是尝试更新其子项,但失败了,因为子项具有必填字段,而我只提供 ID。

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

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

我收到以下错误:

属性:名称错误:请输入名称属性:描述 错误:请输入描述属性:类别错误:请 输入类别

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

c# entity-framework many-to-many
2个回答
1
投票

你应该使用:

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

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

  • Entry方法(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);
}

0
投票

我有一个非常相似的情况,我只是通过为儿童对象添加

state = EntityState.Unchanged
来解决它:

public async Task<ActionResult<int>> Put([FromBody]NewsAlert newsAlertPut)
{

    context.NewsAlerts.Update(newsAlertPut);
    
    //To avoid saving each UserSegment, since here only the Id is provided.
    //With this [for] loop only the ManyToMany relation is updated (NewsAlertUserSegment)
    foreach (var userSegment in newsAlertPut.UserSegments)
    {
        context.Entry(userSegment).State = EntityState.Unchanged;
    }
    
    await context.SaveChangesAsync();

    return newsAlertPut.Id;
}
© www.soinside.com 2019 - 2024. All rights reserved.