![](/img/trans.png)
[英]EF Core, one-to-many relationship - how to insert records in both tables with a single view?
[英]Insert new Entity with one to many relationship not creating records in both tables
我正在使用MVC5和EF6 Code First創建一個可以具有許多Contact
實體的新Company
實體。 但是,只有Company
記錄被寫入數據庫。
楷模:
public class Company
{
public virtual int CompanyId { get; set; }
[Required]
public virtual string Name { get; set; }
[Required]
public virtual Address Address { get; set; }
[Required]
public virtual string Phone { get; set; }
public virtual string Email { get; set; }
// can have many Contacts
public virtual IEnumerable<Contact> Contacts { get; set; }
}
public class Contact
{
public virtual int ContactId { get; set; }
[Required]
public virtual string Title { get; set; }
[Required]
public virtual string Forename { get; set; }
[Required]
public virtual string Surname { get; set; }
[Required]
public virtual string Phone { get; set; }
public virtual string Email { get; set; }
// belongs to one Company
public virtual Company Company { get; set; }
}
控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create_POST([Bind(Include = "CallerType,Name,Address,Phone,Email,Contacts")] CompanyViewModel viewModel)
{
if (ModelState.IsValid)
{
// tried commented code to make sure it wasn't a problem with my repository and contact records aren't saved to database...
//var context = new EfDbContext();
//var company = new Company
//{
// Name = viewModel.Name,
// Phone = viewModel.Phone,
// Address = viewModel.Address,
// Email = viewModel.Email
//};
//context.Companies.Add(company);
//var contact = new Contact
//{
// Company = company,
// Title = "mr",
// Forename= "f",
// Surname = "s",
// Phone = "132"
//};
//var contact2 = new Contact
//{
// Company = company,
// Title = "mr",
// Forename = "for",
// Surname = "sur",
// Phone = "987"
//};
//var contacts = new List<Contact> {contact, contact2};
//company.Contacts = contacts;
//context.SaveChanges();
var contacts = viewModel.Contacts.Select(c => new Contact
{
Title = c.Title,
Forename = c.Forename,
Surname = c.Surname,
Phone = c.Phone,
Email = c.Email
});
var company = new Company
{
Name = viewModel.Name,
Phone = viewModel.Phone,
Address = viewModel.Address,
Email = viewModel.Email,
Contacts = contacts
};
await _companyRepository.CreateAsync(company);
var redirectUrl = new UrlHelper(Request.RequestContext).Action("Create", "Enquiry", new { id = company.CompanyId, callerType = viewModel.CallerType });
return Json(new { Url = redirectUrl });
}
Response.StatusCode = 400;
return PartialView("~/Views/Company/_Create.cshtml", viewModel);
}
倉庫:
public async Task<TEntity> CreateAsync(TEntity entity)
{
if (entity == null) throw new ArgumentNullException(nameof(entity));
DbContext.Set<TEntity>().Add(entity);
await DbContext.SaveChangesAsync();
return entity;
}
我的印象是DbContext
會“知道”,因為填充了Contacts
集合,它將創建鏈接到創建的Company
Contact
記錄。 還是我必須創建Contact
因為這是其中包含外鍵的表,EF會“知道”首先創建Company
嗎?
還是需要首先使用SaveChanges()
實際保存Company
實體,然后將其分配給Contact
記錄並執行第二個SaveChanges()
?
如果是這種情況,那么我需要使用Database.BeginTransaction()
嗎?
關於這方面的任何指導都將是很棒的,因為這是我第一次使用實體框架。
Contacts
必須是ICollection
。 EF不支持將IEnumerable
用作導航屬性,因為無法向其中添加項目。
這也意味着您應該更改創建contacts
的代碼:
var contacts = viewModel.Contacts.Select(c => new Contact
{
Title = c.Title,
Forename = c.Forename,
Surname = c.Surname,
Phone = c.Phone,
Email = c.Email
}).ToList(); // <= ToList() added
您的關系應通過覆蓋OnModelCreating方法在DbContext中建立
我本人是Entity Framework的新手,但發現方法名稱有助於學習如何建立關系
希望以下內容能對您有所幫助
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Company>()
.HasMany(c => c.Contacts)
.WithRequired(co => co.Company)
.HasForeignKey(co => co.CompanyId);
}
您還可以在您的關系中設置級聯,這樣,當刪除一個實體時,相關實體也將被刪除,如果您需要刪除公司,可能需要考慮這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.