2014-11-06 105 views
0

鉴于以下代码,我试图将复杂对象Institution保存到数据库。如果我拿出引用来解决基本机构正确保存但添加了地址,我得到一个外键错误,并没有保存。什么是拯救复杂课堂的正确方法?通过Entity Framework将复杂模型保存到数据库5

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

你必须先主要实体保存到数据库,生成它的ID,如果它的自动递增。然后将其分配给您的地址对象。这就是为什么建议您为每个对象创建单独的存储库类。 – DevEstacion 2014-11-06 02:21:32

+0

这就是我所期待的。我只是不确定是否有内置的方法。 – 2014-11-06 02:25:08

回答

0

您可以通过重写OnModelCreating控制一个一对多的关系(和外键的定义)在你的DbContext中。类似于以下内容的内容应该可以工作:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
    modelBuilder.Entity<Institution>().HasMany<Address>(i => i.Addresses) 
     .WithRequired(i => i.Institution).HasForeignKey(i => i.Id); 
} 
0

使用构造函数定义机构。

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(); 
相关问题