【问题标题】:Entity Framework Core - Call A Populate Extension Method Inside IncludeEntity Framework Core - 在 Include 中调用填充扩展方法
【发布时间】:2019-01-21 10:36:01
【问题描述】:

我会用一个例子来解释我的问题。 假设我有以下类和方法(我仅为此示例创建它们)

  public class Student
    {
        public string Name { get; set; }
        public string Id { get; set; }

        public Subject Expertise { get; set; }
    }

    public class Subject
    {
        public string Name { get; set; }
        public Teacher Teacher { get; set; }
    }

    public class Teacher
    {
        public string Name { get; set; }
        public string LicenseId{ get; set; }
        public License License { get; set; }

    }
    public class License
    {
        public string LicsenseType;
    }

    public static IQueryable<Subject> PopulateWithTeacherAndLicense(this IQueryable<Subject> subjects)
    {

        return subjects
            .Include(c => c.Teacher)
                .ThenInclude(p => p.License);
        
    }

现在假设我想选择所有学生及其所有学科、教师和执照。为此,我想使用我的 PopulateWithTeacherAndLicense。我希望查询看起来像:

db.Students.Include(s =&gt; s.Expertise.PopulateWithTeacherAndLicense())

而且不必做Include(s=>s.Expertise).TheInclude(s => s.Teacher)...

【问题讨论】:

  • .. 这不适合你吗?你有什么问题?
  • 我收到此错误:表达式应表示属性访问:'t => t.MyProperty
  • 如果在调用语句中使用返回类型,它将如下所示:db.Students.Include(s => s.Expertise.subjects.Include(c => c.Teacher)。 ThenInclude(p => p.License));我认为这不是您打算进行的操作,还是我要进行的操作?
  • 我带来的例子只是一个简单的例子来解释我的问题。一般的问题是如何使用一组包含,然后包含我已经包装在内的语句作为实体的扩展方法。例如,如果我创建了一个填充所有主题图的扩展方法,我希望能够在我想用他的完整图选择学生时使用它(不需要重复所有的 Include 和 ThenInclude 语句)。我希望我成功地解释了自己:-)

标签: c# entity-framework-6 entity-framework-core


【解决方案1】:

您可以为Student集合本身创建扩展方法

public static IQueryable<Student> IncludeExpertise(this IQueryable<Student> students)
{
    return students
        .Include(s => s.Expertise)
        .ThenInclude(c => c.Teacher)
        .ThenInclude(p => p.License);

}

【讨论】:

  • 是的,但是如果对象图很大,再次复制所有代码感觉很不对
猜你喜欢
  • 2019-06-27
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多