实体框架:获取Repository中的Subclass对象

时间:2012-07-27 07:44:52

标签: c# .net entity-framework design-patterns domain-driven-design

我有以下模型,对应于下面列出的数据库表。

经理是员工。会计师也是雇员。

  1. 获取存储库中所有管理员的最佳方法是什么?如何实现GetAllManagers()方法?
  2. TPT是否合适?
  3. enter image description here

    CODE

    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;
        }
    
    
    
    }
    

    修改

    这种模式有缺点。它应该考虑以下:

    1. 可以为他创建没有任何角色的员工。
    2. 一名员工可以拥有多个角色。

1 个答案:

答案 0 :(得分:2)

只是做:

return context.Employees.OfType<Accountant>().ToList()

然而,这是对员工进行建模的一种非常糟糕的方式..如果会计师更改了工作,您需要杀死并重新创建该对象..

请参阅Inheritance vs enum properties in the domain model上的答案。