简体   繁体   English

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

[英]Saving a complex model to DB via Entity Framework 5

Given the following code, I am trying to save the complex object Institution to the db. 给定以下代码,我试图将复杂对象Institution保存到db。 If I take out references to address the base institution saves correctly but with the Address added in I get a foreign key error and nothing saves. 如果我删除对地址的引用,则正确地保存了基础机构,但是添加了地址后,我得到了外键错误,并且没有任何保存。 What is the correct way to save a complex class? 保存复杂类的正确方法是什么?

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

The institution class: 机构类别:

 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; }
}

The address class: 地址类别:

 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; }
}

You can control the one-to-many relationship (and the foreign key definition) by overriding the OnModelCreating in your DbContext. 您可以通过覆盖DbContext中的OnModelCreating来控制一对多关系(以及外键定义)。 Something similar to the following should work: 类似以下内容应起作用:

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

Define Institution with the a constructor. 使用构造函数定义机构。

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; }
}

Then you can write your add code like the following 然后,您可以编写如下的添加代码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM