【问题标题】:Entity Framework Mapping to Lookup table实体框架映射到查找表
【发布时间】:2011-12-18 18:39:32
【问题描述】:

我有 3 个表需要使用 Entity Framework 进行映射,但我不确定执行此操作的正确方法。这是我的 3 个实体:

public class User
{
   [Key] 
   public int user_id {get; set;}
   public string user_name {get; set;}

   public virtual List<Role> roles {get; set;}
}

public class Role
{
   [Key] 
   public int role_id {get; set;}

   public string role_name {get; set;}
}

public class User_Role
{
   [Key] 
   public int user_role_id {get; set;}

   public int user_id {get; set;}
   public int role_id {get; set;}
}

请注意,User_Role 实体仅代表一个查找表,用于将多个角色链接到单个用户。

使用 SQL,我会执行以下操作:

SELECT User.user_name, Role.role_name FROM User INNER JOIN User_Role ON User_Role.user_id = User.user_id INNER JOIN Role ON Role.role_id = User_Role.role_id WHERE User.user_id = 123

我对 Entity Framework 比较陌生,所以我不确定使用 EF4 DbContext(可能还有 Fluent API?)解决这个问题的最佳方法,但我希望它非常简单。

提前致谢。

【问题讨论】:

    标签: entity-framework entity-framework-4 mapping inner-join lookup


    【解决方案1】:

    原来我需要使用 Fluent API 来映射多对多表 (User_Role)。

         modelBuilder.Entity<Role>()
            .HasMany<User>(u => u.users)
            .WithMany(r => r.roles)
            .Map(m => 
               m.MapLeftKey("role_id")
               m.MapRightKey("user_id")
               m.ToTable("User_Role"));
    

    【讨论】:

    • 请显示此功能所需的模型更新。例如。您的原始帖子中的任何实体都没有 users 属性。
    猜你喜欢
    • 2015-08-17
    • 2014-04-01
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多