通过Entity Framework 5将复杂模型保存到DB

时间:2014-11-06 02:13:40

标签: c# entity-framework entity-framework-5

鉴于以下代码,我试图将复杂对象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; }
}

2 个答案:

答案 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();