相关疑难解决方法(0)

EF包含其他实体(通用存储库模式)

我在Entity Framework Code First上使用Generic Repository模式.一切都工作正常,直到我需要在查询中包含更多实体.我成功地包含了一个实体,但现在我无法弄清楚如何包含多个实体.看看到目前为止我得到了什么:

public IQueryable<TEntity> GetQuery<TEntity>() where TEntity : class
{
    var entityName = GetEntityName<TEntity>();
    return _objectContext.CreateQuery<TEntity>(entityName);
}

public IList<TEntity> GetQueryWithInclude<TEntity>(string toInclude) where TEntity : class
{
    var entityName = GetEntityName<TEntity>();
    return _objectContext.CreateQuery<TEntity>(entityName).Include(toInclude).ToList();
}

private string GetEntityName<TEntity>() where TEntity : class
{
    return string.Format("{0}.{1}", _objectContext.DefaultContainerName, _pluralizer.Pluralize(typeof(TEntity).Name));
}
Run Code Online (Sandbox Code Playgroud)

我尝试但没有工作的是将一个字符串数组传递给一个函数,然后尝试在查询之上"追加"包含.我在想,如果我叫GetQueryWithInclude并在同一时间聚集查询的结果通过了实体名称(实际导航性能),但我担心这可能会重复在每次调用查询的结果...您认为最好的方法是什么?

提前致谢!

更新:

这是我想要实现的一个例子:

public IQueryable GetQueryWithIncludes(string[] otherEntities)
{
    var entityName = GetEntityName<TEntity>();
    //now loop over the otherEntities array 
    //and append Include extensions to the query
    //so inside the loop, something …
Run Code Online (Sandbox Code Playgroud)

c# entity-framework repository-pattern entity-framework-4 ef-code-first

67
推荐指数
2
解决办法
5万
查看次数

如何首先急切地加载与实体框架代码的多对多关系?

为了清楚起见,我将给出我能想到的最基本的例子.

可以说我有两个以下形式的实体:

public class Student
{
    public int Id {get;set}
    public string FullName {get;set;}
    public virtual ICollection<Course> Courses {get;set;}
}

public class Courses
{
    public int Id {get;set;}
    public string FullName {get;set;}
    public virtual ICollection<Student> Students {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

这两个实体映射到三个表,第三个表是连接的表.

当我像这样查询学生时

var allStudents = context.Students;
Run Code Online (Sandbox Code Playgroud)

然后遍历结果以显示学生及其课程列表

foreach (var student in allStudents) 
{
    display(student.FullName);
    foreach (var course in student.Courses) 
    {
        display(course.FullName);
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到第一个查询返回的每个学生的课程查询.

如何通过一个查询告诉实体框架急切地将课程加载到学生中?

database many-to-many entity-framework eager-loading ef-code-first

4
推荐指数
1
解决办法
3110
查看次数