鉴于以下代码,我试图将复杂对象Institution保存到db。如果我拿出引用来解决基础机构正确保存但是添加了地址我得到了一个外键错误,没有任何保存。保存复杂类的正确方法是什么?
Institution inst = new Institution();
inst.Name = "Institution Name";
Address address = new Address();
address.Street1 = "1234 west main";
address.City = "Gotham";
address.State = "WI";
address.PostalCode = "55555";
List<Address> addresses = new List<Address>();
addresses.Add(address);
inst.Addresses = addresses;
db.Institutions.Add(inst);
db.SaveChanges();
机构类:
public class Institution
{
[Key]
public int ID { get; set; }
[Display(Name="Institution Name")]
public string Name { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
}
地址类:
public class Address
{
[Key]
public int Id { get; set; }
[Display(Name = "Street")]
public string Street1 { get; set; }
[Required]
public string City { get; set; }
[Required]
[MaxLength(2)]
public string State { get; set; }
[Display(Name = "Zip")]
public string PostalCode { get; set; }
public virtual Institution Institution { get; set; }
public virtual AddressType AddressType { get; set; }
}
答案 0 :(得分:0)
您可以通过覆盖DbContext中的OnModelCreating来控制一对多关系(和外键定义)。类似于以下内容应该有效:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Institution>().HasMany<Address>(i => i.Addresses)
.WithRequired(i => i.Institution).HasForeignKey(i => i.Id);
}
答案 1 :(得分:0)
使用构造函数定义Institution。
public class Institution
{
public Institution()
{
Addresses = new Addresses<Student>();
}
[Key]
public int ID { get; set; }
[Display(Name="Institution Name")]
public string Name { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
}
然后您可以编写添加代码,如下所示
Institution inst = new Institution();
inst.Name = "Institution Name";
Address address = new Address();
address.Street1 = "1234 west main";
address.City = "Gotham";
address.State = "WI";
address.PostalCode = "55555";
inst.Addresses.Add(addresses);
db.Institutions.Add(inst);
db.SaveChanges();