实体框架多个选择一个数据库调用

时间:2013-09-20 22:36:00

标签: linq entity-framework

这是我的课程(我使用的是Entity Framework 5; .Net Framework 4.0):

public class Role
{
public int RoleId { get; set; }
public string Name { get; set; }


[NotMapped]
public List<RolePrompt> RolePrompts { get; set; }

[NotMapped]
public List<RoleFeature> RoleFeatures { get; set; }
}

public class RolePrompt
{
  public int RolePromptId{get;set;}
  public int RoleId{get;set;}
  public int PromptId{get;set;}

  public Role Role{get;set;}
}

public class RoleFeature
{
  public int RoleFeatureId{get;set;}
  public int RoleId{get;set;}
  public int FeatureId{get;set;}

  public Role Role{get;set;}
}

如何使用一个db调用填充所有子对象来加载Role对象?我知道如何使用多个存储库调用来完成它。

Role role = roleRepository.Find(roleId);
role.RolePrompts = rolePromptsRepository.FindByRoleId(roleId); 
role.RoleFeatures = roleFeaturesRepository.FindByRoleId(roleId);

......等等

上面的代码多次调用DB。我希望在一次数据库调用中使用RolePrompts和RoleFeatures加载Role对象。

2 个答案:

答案 0 :(得分:0)

我创建了一个小帮手方法来做到这一点。

public virtual IQueryable<T> Include(params Expression<Func<T, object>>[] includes)
{
    IQueryable<T> dbQuery = context.Set<T>();

    // Apply eager loading
    foreach (Expression<Func<T, object>> inc in includes)
    {
        dbQuery = dbQuery.Include<T, object>(inc);
    }

    return dbQuery.AsNoTracking();
}

'context'是我设置的包含当前DbContext

的类的属性

然后你可以通过这样做来调用它

var myData = context.Roles.Where(x => x.RoleId == roleid).Include("RolePrompts", "RoleFeatures")

答案 1 :(得分:0)

根据您的评论:

  

与角色和要素表有多对多的关系,与角色和提示表有一对多的关系。

你需要这个类结构:

public class Role
{
    public int RoleId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<RoleFeature> RoleFeatures { get; set; }

    public virtual ICollection<RolePrompt> RolePrompts { get; set; }
}

public class RolePrompt
{
    public int RolePromptId { get; set; }

    public virtual Role Role { get; set; }
}

public class RoleFeature
{
    public int RoleFeatureId { get; set; }

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

modelBuilder.Entity<Role>()
.HasMany(r => r.RoleFeatures).WithMany(f => f.Roles)
.Map(t => t.MapLeftKey("RoleId")
    .MapRightKey("RoleFeatureId")
    .ToTable("RoleRoleFeatures"));

这将为您提供此表结构:

Table Structure

然后您可以继续使用Include加载PromptsFeatures