2

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

控制器

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);即使我的 Hospital 实例充满了数据。如何准确地将数据保存到两个表中,dbo.Operators哪个dbo.OperatorHospital是关系表?

4

1 回答 1

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

}

于 2012-05-15T19:10:57.220 回答