2
當使用EF 4.3代碼第一種方法創建多對多關係時,我無法將數據保存到連接表中,也無法使用保存對象將其填充到Icollection的任何示例...以下是我的示例:Entity Framework 4.3 CF多對多關係保存對象?
模型
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 = "[email protected]";
o.Hospitals.Add(h);
db.SaveChanges();
}
用這種方法我一直GETT錯誤在這裏:o.Hospitals.Add(h);
即使我的醫院實例充滿了數據。如何將數據保存到兩個表中,dbo.Operators
和dbo.OperatorHospital
哪個是關係表?
謝謝,現在工作得很好! –