2011-09-16 59 views
0

我在提交實體框架代碼第一個應用程序的第三個導航屬性上的數據時遇到問題。實體框架代碼 - 第一次保存許多到多次

我的模式是這樣的:(假設有一個模式叫用戶和公司)

public enum UserCompanyRoleType 
{ 
    Administrator, 
    Creator, 
    Follower 
} 
/// <summary> 
/// User that belongs to a company 
/// </summary> 
public class UserCompany 
{ 

    public int UserCompanyId { get; set; } 

    public virtual User User { get; set; } 
    public virtual int UserId { get; set; } 

    public virtual Company Company { get; set; } 
    public virtual int CompanyId { get; set; } 

    public virtual IEnumerable<UserCompanyRole> Roles { get; set; } 
} 

public class UserCompanyRole 
{ 

    public virtual int UserCompanyRoleId { get; set; } 
    public UserCompanyRoleType RoleType { get; set; } 

    public virtual UserCompany UserCompany { get; set; } 
    public virtual int UserCompanyId { get; set; } 

} 

這裏的服務代碼:

var creator = new UserCompany { UserId = userId }; 
//add the user as both creator and admin 
creator.Roles = new List<UserCompanyRole> { new UserCompanyRole{RoleType = UserCompanyRoleType.Creator}}; //somehow this does not reach the database 

company.Users = new List<UserCompany>(); 
company.Users.Add(creator); 

db.Companies.Add(company); 
db.SaveChanges(); 

這既節省了企業和相關usercompany ,但這2個角色沒有保存。我如何在我評論的這條線上保存這兩個角色?

回答

1

您需要將Roles屬性設置爲ICollection<UserCompany>類型。

public class UserCompany 
{ 

    public int UserCompanyId { get; set; } 

    public virtual User User { get; set; } 
    public virtual int UserId { get; set; } 

    public virtual Company Company { get; set; } 
    public virtual int CompanyId { get; set; } 

    public virtual ICollection<UserCompanyRole> Roles { get; set; } 
} 

枚舉沒有在EF 4.1的支持,所以你將不得不使用int字段映射該屬性。

+0

爲什麼ICollection在IEnumerable上工作?我應該把所有的代碼改成那個嗎? –

+0

@Lol檢查[爲什麼實體框架需要ICollection進行延遲加載](http://stackoverflow.com/questions/2866881/why-does-the-entity-framework-need-an-icollection-for-lazy-加載) – Eranga