0

我有一个看起来像这样的上下文:

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

但我遇到了同样的问题。

是否有可能让它工作,或者我必须以某种方式做不同的事情?

4

1 回答 1

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; }
}
于 2013-01-16T15:16:20.867 回答