[英]EF Core Update Linked Object
我正在尝试使用 EF Core 更新公司及其联系方式,如示例 JSON 请求中所示
PUT https://localhost:6001/api/Company
{
"CompanyId": 6,
"Name": "string",
"ContactDetail": {
"Name": "string",
"EmailAddress": "string",
"Address1": "string",
"Address2": "string",
"Address3": "string",
"PostCode": "string",
"Telephone": "string"
}
}
生成的 EF Scaffold 长这个样子
public partial class Company
{
public long CompanyId { get; set; }
public string Name { get; set; }
public virtual ContactDetail ContactDetail { get; set; }
}
public partial class ContactDetail
{
public ContactDetail()
{
Company = new HashSet<Company>();
}
public long ContactDetailId { get; set; }
public string Name { get; set; }
public string EmailAddress { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string Address3 { get; set; }
public string PostCode { get; set; }
public string Telephone { get; set; }
public virtual ICollection<Company> Company { get; set; }
}
我怎样才能以最干净的方式更新 ContactDetail,如果我要提供 ContactDetailId 那么我认为它会正常工作,但理想情况下我只想提供父对象的 CompanyId。 以下代码更新了公司,但为 ContactDetail 创建了一个新条目!?
public Copmany Update(Copmany company)
{
_bigLoaderContext.Update(company);
_bigLoaderContext.SaveChanges();
return GetById(company.CompanyId);
}
更新 - 我现在使用的一个解决方案是获取 ContactDetail id,然后将其重新分配给对象。
public Company Update(Company company)
{
var currentCompany = GetById(companyId, true);
// Update the contact detail id so that it know what one to update
company.ContactDetail.ContactDetailId = currentCompany.ContactDetailId;
_bigLoaderContext.Update(company);
_bigLoaderContext.SaveChanges();
}
我得到了一个错误加载对象来获取值,所以不得不用在GetById方法AsNoTracking得到它。
_bigLoaderContext.Company.AsNoTracking().FirstOrDefault(f => f.CompanyId == companyId);
我现在使用的一个解决方案是获取 ContactDetail id,然后将其重新分配给对象。
public Company Update(Company company)
{
var currentCompany = GetById(companyId, true);
// Update the contact detail id so that it know what one to update
company.ContactDetail.ContactDetailId = currentCompany.ContactDetailId;
_bigLoaderContext.Update(company);
_bigLoaderContext.SaveChanges();
}
我在加载对象以获取值时遇到错误,因此必须使用 GetById 方法中的 AsNoTracking 来获取它。
_bigLoaderContext.Company.AsNoTracking().FirstOrDefault(f => f.CompanyId == companyId);
假设这没问题,因为它有效!?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.