在实体框架中加载不相关的导航属性

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

我面临着一个特殊的场景。我希望能够通过实体框架将“不相关”的数据加载到域实体中。

例如;取以下实体

class Employee{
 public int Id {get;set;}
 public int Department {get;set;}
 public Department DepartmentNavigation {get;set;}
 // the following property is not mapped => but needed for domain logic
 // this property should contain all the departments available in the company. 
 // I.E => all rows in the departments table
 public ICollection<Department> AllAvailableDepartments {get;set;}
}

有没有办法在实体配置期间在 DBContext 内包含此属性?以下是一段假设的代码。

entity.Property(e=>e.AllAvailableDepartments).FromSql("select * from Departments");

我希望每次填充

Employee
实体时都填充此属性。这样这些数据可用于
Employee
实体内的域逻辑。

我想过使用

static
变量来维护这些数据,以便
Employee
实体可以访问这些数据,但这个想法很糟糕!如果“部门”数据发生更改并且静态数据未反映这些更改怎么办?

c# entity-framework .net-core
1个回答
0
投票

我希望能够将“不相关”的数据加载到域实体中

从设计角度来看,这不是最佳选择。有时,您可以为了更简单的用例而使用实体作为域对象,但这仍然是一个持久性问题。

可用于领域逻辑

如果您需要在域逻辑中为特定用例塑造数据,可能更直接的方法是引入一个类和一个存储库来满足您的需要。比依赖 ORM 更容易推理和调试。

为了说明我的观点:

public class Employee {
   public int Id {get; set;}
   public int Department {get; set;}
   public Department DepartmentNavigation {get; set;}
}

public class Department
{
   public int Id {get; set;}
   public string Name {get; set;}
}

public class EmployeeDepartmentResult
{
   public Employee {get; set;}
   public ICollection<Departments> AllAvailableDepartments {get; set;}
}

public class EmployeeDepartmentRepository
{
    public EmployeeDepartmentResult GetByEmployeeId(int employeeId)
    {
        Employee employee = db.Employees.FirstOrDefault(e = > e.Id == employeeId);
        ICollection<Departments> availableDepartments = db.Departments.Where(...).ToList();

        return new EmployeeDepartmentResult
        {
            Employee = employee;
            AllAvailableDepartments = availableDepartments ;
        }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.