问题:
我无法创建和实体并将其保存到数据库。实体表示拥有personal_data实体(组成)的客户,最后一个在组成中也具有和地址,并且地址具有与现有实体的关系。
型号和代码:
型号:
[Table("customers")]
public class Customer
{
public int ID { get; set; }
public string comments { get; set; }
public virtual PersonalData personal_data { get; set; }
public virtual User User { get; set; }
}
[Table("personal_datas")]
public class PersonalData
{
[Key]
[Column("id")]
public int ID { get; set; }
public string name { get; set; }
...
public virtual Address address { get; set; }
}
[Table("addresses")]
public class Address
{
public int ID { get; set; }
public string address1 { get; set; }
...
public int region_id { get; set; }
[ForeignKey("region_id")]
public virtual Region region { get; set; }
}
[Table("regions")]
public class Region
{
public int ID { get; set; }
[LocalizedDisplayName("Nombre")]
public string name { get; set; }
public virtual Country country { get; set; }
}
代码:
Customer customer = new Customer();
customer.comments = "XXX";
customer.personal_data = new PersonalData();
customer.personal_data.last_name_1 = "";
customer.personal_data.last_name_2 = "";
customer.personal_data.address = new Address();
customer.personal_data.address.address1 = "";
customer.personal_data.address.cp = "";
customer.personal_data.address.city = "";
customer.personal_data.address.region_id = 0;
db.Entry(customer).State = EntityState.Added;
db.Entry(customer.personal_data).State = EntityState.Added;
db.Entry(customer.personal_data.address).State = EntityState.Added;
db.SaveChanges();
错误:
'保存不公开其关系的外键属性的实体时发生错误。 EntityEntries属性将返回null,因为无法将单个实体标识为异常的来源。通过在实体类型中公开外键属性,可以简化保存时的异常处理。有关详细信息,请参见InnerException。'
重点是,这可以在控制器上执行编辑操作:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ID,comments,personal_data")] Customer customer)
{
if (ModelState.IsValid)
{
db.Entry(customer).State = EntityState.Modified;
db.Entry(customer.personal_data).State = EntityState.Modified;
db.Entry(customer.personal_data.address).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Edit", new { id = customer.ID });
}
return View(customer);
}
任何想法?
修改
我已将“地址”添加到“区域”:
public ICollection<Address> Addresses { get; set; }
然后在“ OnModelCreating”中输入:
modelBuilder.Entity<Address>()
.HasRequired<Region>(s => s.region)
.WithMany(g => g.Addresses)
.HasForeignKey<int>(s => s.region_id);
该错误仍然存在。
答案 0 :(得分:0)
您需要向数据库上下文提供外键,以便EF可以在创建时满足它。我不知道您的数据库布局,但是在上下文中,一对多关系看起来像下面的样子
this link should be helpful with setup as well
modelBuilder.Entity<MyModel>(entity =>
{
...removed other configuration for brevity
entity.HasOne(d => d.MyOtherModel)
.WithMany(p => p.MyModel)
.HasForeignKey(d => d.MyModelKey)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_My_Foreign_Key_Name");
});