实体框架:获取存储库中的子类对象 [英] Entity Framework: Get Subclass objects in Repository
本文介绍了实体框架:获取存储库中的子类对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下列出的数据库表中的以下模型。
I have following model corresponding to the database tables listed below.
经理是一名员工。会计师也是一名员工。
A manager is an employee. An accountant also is an employee.
- 在存储库中获取所有管理员的最佳方法是什么?如何实现GetAllManagers()方法?
- TPT是否正确?
代码
MyRepository.MyEmployeeRepository rep = new MyEmployeeRepository();
List<Employee> e = rep.GetAllEmployees();
public class MyEmployeeRepository
{
private string connectionStringVal;
public MyEmployeeRepository()
{
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
sqlBuilder.DataSource = ".";
sqlBuilder.InitialCatalog = "LibraryReservationSystem";
sqlBuilder.IntegratedSecurity = true;
// Initialize the EntityConnectionStringBuilder.
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.Provider = "System.Data.SqlClient";
entityBuilder.ProviderConnectionString = sqlBuilder.ToString();
entityBuilder.Metadata = @"res://*/Test.csdl|res://*/Test.ssdl|res://*/Test.msl";
connectionStringVal = entityBuilder.ToString();
}
public List<Employee> GetAllEmployees()
{
List<Employee> employees = new List<Employee>();
using (var context = new MyEntityDataModelEDM.LibraryReservationSystemEntities1(connectionStringVal))
{
foreach (MyEntityDataModelEDM.Employee p in context.Employees)
{
employees.Add(p);
}
}
return employees;
}
public List<Manager> GetAllManagers()
{
List<Manager> managers = new List<Manager>();
using (var context = new MyEntityDataModelEDM.LibraryReservationSystemEntities1(connectionStringVal))
{
}
return managers;
}
}
编辑
此模型有缺点。应该考虑以下内容:
This model has drawbacks. It should consider following:
- 员工可以创建,没有任何角色。
- 可以有多个角色。
推荐答案
只需执行:
return context.Employees.OfType<Accountant>().ToList()
然而,这是模拟员工的一个非常糟糕的方法..如果会计师改变工作,您需要杀死并重新创建该对象。
This is however a really bad way to model employees.. if an accountant changes job, you need to kill and recreate that object..
请参阅我的答案关于继承与枚举属性域模型。
这篇关于实体框架:获取存储库中的子类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文