2013-01-16 89 views
0

我有一個背景下,看起來像這樣:許多一對多的實體框架(DB頭)與POCO類關係

public DbSet<User> Users { get; set; } 
public DbSet<AccessGroup> AccessGroups { get; set; } 
public DbSet<UserAccessGroup> UsersAccessGroups { get; set; } 

數據庫有三個表:

  • 用戶[PK = Id,...]
  • AccessGroups [Pk = Id,...]
  • UsersAccessGroups [Pk = Id,Fk = UserId,Fk = AccessGroupId,...]好吧)

我們有三類:

public class User 
{ 
    public virtual int Id { get; set; } 
    public virtual ICollection<UserAccessGroup> UsersAccessGroups { get; set; } 
    // Some more.. 
} 

public class AccessGroup 
{ 
    public virtual int Id { get; set; } 
    public virtual ICollection<UserAccessGroup> UsersAccessGroups { get; set; } 
    // Some more.. 
} 

[Table("UsersAccessGroups")] 
public class UserAccessGroup 
{ 
    public virtual int Id { get; set; } 
    public virtual int UserId { get; set; } 
    public virtual int AccessGroupId { get; set; } 
    public virtual int CreatedByUserId { get; set; } 
    public virtual DateTime CreatedAt { get; set; } 

    public virtual User User { get; set; } 
    public virtual AccessGroup AccessGroup { get; set; } 
    public virtual User CreatedByUser { get; set; } 
} 

我希望能夠使用一個用戶對象是這樣的:

var user = Context.Users.Select(x => x); 
var accessGroup = user.UsersAccessGroups.Select(x => x.AccessGroup).ToList(); 

第二行不不但是工作。我收到錯誤說「無效的列名User_Id」 當我有一對一的關係時(如CreatedByUser),相同的代碼工作。

我也嘗試過這樣的事情:

Context.Users.Include("UsersAccessGroups") 
    .Include("UsersAccessGroups.AccessGroup") 
    .Include("UsersAccessGroups.User").Select(...); 

,但我得到了同樣的問題。

是否有可能得到這個工作,或者我必須以不同方式做它不同?

回答

0

您需要爲CreatedByUser指定外鍵,因爲EF無法按照慣例映射它。

[Table("UsersAccessGroups")] 
public class UserAccessGroup 
{ 
    public virtual int Id { get; set; } 
    public virtual int UserId { get; set; } 
    public virtual int AccessGroupId { get; set; } 
    public virtual int CreatedByUserId { get; set; } 
    public virtual DateTime CreatedAt { get; set; } 

    public virtual User User { get; set; } 
    public virtual AccessGroup AccessGroup { get; set; } 
    [ForeignKey("CreatedByUserId")] 
    public virtual User CreatedByUser { get; set; } 
}