我想更新与其他记录具有多对多关系的记录。 我的问题是,它总是尝试更新其子项,但失败了,因为子项具有必填字段,而我只提供 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 它只应该插入地址并更新关系表。我不想通过先加载产品来产生开销。我也不喜欢在不必要时访问产品表。
你应该使用:
Attach 用于使用已知的实体重新填充上下文 数据库中已存在
您可能还想阅读添加/附加和实体状态
对于许多产品:
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);
}
我有一个非常相似的情况,我只是通过为儿童对象添加
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;
}