实体框架4.3 CF多对多关系保存对象?

时间:2012-05-15 19:02:31

标签: entity-framework many-to-many entity-framework-4.3 savechanges

当使用EF 4.3代码创建多对多关系的第一种方法时,我无法将数据保存到连接表,也无法使用保存对象来填充此表的任何示例到Icollection ...这是我的例子:

模型

public class Hospital
{
    //PK
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string County { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public Guid User_Id { get; set; }

    //FK
    public virtual ICollection<Operator> Operators { get; set; }

}

public class Operator
{
    //PK
    [Key]
    public int Id { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime Dob { get; set; }
    public string Email { get; set; }

    //FK
    public virtual ICollection<Hospital> Hospitals { get; set; }
}

public class Project: DbContext
{
    public DbSet<Hospital> Hospitals { get; set; }
    public DbSet<Operator> Operators { get; set; }
}

CONTROLLER

public void AddOperater()
{

    Hospital h = new Hospital();
    h = db.Hospitals.Single(a=>a.Id ==1);

    var o = new Operator();
    o.FirstName = "John";
    o.LastName = "Doe";
    o.Dob = new DateTime(1988,2,12);
    o.Email = "johndoe@gmail.com";
    o.Hospitals.Add(h);

    db.SaveChanges();
 }

通过这种方法,我在这里不断收到错误:o.Hospitals.Add(h);即使我的医院实例充满了数据。如何将数据保存到两个表,dbo.Operatorsdbo.OperatorHospital这是关系表?

1 个答案:

答案 0 :(得分:3)

o.Hospitals.Add(h)将失败,因为列表是空列表。您不能在空列表上调用Add()。通常,大多数人通过在实体的构造函数中实例化列表来解决这个问题......就像这样......由于CSharp问题,当前行正在爆炸。

public class Hospital
{
    //PK
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string County { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public Guid User_Id { get; set; }

     //FK
    public virtual ICollection<Operator> Operators { get; set; }

    public Hospital()
    {
         Operators = new List<Operator>();
    }

}


public class Operator
{
   //PK
   [Key]
   public int Id { get; set; }

   public string FirstName { get; set; }
   public string LastName { get; set; }
   public DateTime Dob { get; set; }
   public string Email { get; set; }

   //FK
   public virtual ICollection<Hospital> Hospitals { get; set; }

   public Operator()
   {
       Hospitals = new List<Hospital>();
   }

}