使用 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
是关系表?