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.Operatorsdbo.OperatorHospital哪個是關係表?

回答

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

}

+0

謝謝,現在工作得很好! –

相關問題