自动包含实体框架属性

问题描述 投票:0回答:1

我的问题的答案可能微不足道,但我不知道该怎么做。

假设我们有以下情况:

具有嵌套属性的数据库第一个EF实体:

public partial class Employee
{
     public int ID { get; set;}
     public virtual ICollection<EmployeeDepartmentHistory> EmployeeDepartmentHistory { get; set;}
     public virtual ICollection<JobCandidate> JobCandidate { get; set;}
}

域类Employee

(相关类对此示例无所谓)

public class Employee
{
     public int ID { get; set;}
     public IEnumerable<Department> Departments { get; set;}
     public IEnumerable<JobCandidate> Candidates { get; set;}
}

将业务规则应用于查询的服务类EmployeeService

public class EmployeeService
    private RepoTestEntities1 _Database;

    public EmployeeService(RepoTestEntities1 database)
    {
        _Database = database;
    }

    public IQueryable<DomainModels.Employee> GetSalariedEmployeesByDepartmentName(string departmentName)
    {
        _Database.Configuration.LazyLoadingEnabled = false;
        return _Database.Employee
            .Include(e => e.EmployeeDepartmentHistory)
            .Include(e => e.JobCandidate)
            .Include(e => e.EmployeeDepartmentHistory.Select(his => his.Department))
            .AsNoTracking()
            .WhereDepartmentName(departmentName)
            .WhereSalariedFlag(true)
            .Select(e => CreateEmployee(e));
    }
    private DomainModels.Employee CreateEmployee(Employee e)
    {
        [...] (transform to domain)
    }

[WhereDepartmentNameWhereSalariedFlag被实现为IQueryable<Employee>的扩展方法。

现在是问题


假设我需要其他方法,这些方法可从DbContext检索Employees,而我不想使用延迟加载。

反复调用所有这些步骤是多余的,容易出错且乏味的。您知道始终包含[​​C0]的所有方法所需的属性的一种优雅方式吗?

策略模式可能是可行的方法吗?

我的问题的答案可能微不足道,但是我不知道该怎么做。假设我们处于以下情况:具有嵌套属性的数据库第一个EF实体:public部分类Employee ...

c# entity-framework lazy-loading
1个回答
0
投票

如果您确实需要包括所有导航属性,则可以使用这段代码。如果您需要同时加载集合(并非总是一个好主意),则可以删除代码中的continue语句。上下文就是您的上下文(如果在上下文中插入此代码,则为EmployeeService

© www.soinside.com 2019 - 2024. All rights reserved.