关于 DbSet 和判别器

about DbSet and Discriminator

我想使用 Discriminator 属性过滤 DbSet 的行。为了进一步解释,我有一个名为 Employee 的 table,它包含 Discriminator 属性以指定 Employee 是简单的 Employee 还是 Administrator。我想更改员工控制器中的索引视图以仅显示员工而不显示管理员。 这是当前代码:

    //
    // GET: /Employes/

    public ActionResult Index()
    {
        return View(db.Employees.ToList());
    }

我想做成这样:

//
    // GET: /Employee/

    public ActionResult Index()
    {
        return View(db.Employees.Where<Employee>(emp => emp.Discriminator.Equals("Employee")));
    }

但它不起作用,因为 class Employee 不包含属性 Discriminator。有没有不使用 SqlConnection 和 SqlCommand 的其他选择?

这是我的模型 classes :

public class Employee : Person
{
    [Key, ScaffoldColumn(false), Display(Name = "ID")]
    public int idAdmin { set; get; }

    [Required, StringLength(16), Display(Name = "Login")]
    public string loginAdmin { set; get; }

    [Required, StringLength(16), Display(Name = "Password"), DataType(DataType.Password)]
    public string passwordAdmin { set; get; }

    [Required, Display(Name = "CIN")]
    public int cinAdmin { set; get; }
}

public class Administrateur : Employee
{
}
db.Employees.Where(emp => !db.Administrators.Any(a => a.Id == emp.Id));

这将创建以下 SQL

SELECT 
    [Extent1].[Discriminator] AS [Discriminator], 
    [Extent1].[Id] AS [Id], 
    [Extent1].[EmployeeRole] AS [EmployeeRole], 
    [Extent1].[Age] AS [Age], 
    [Extent1].[AdminName] AS [AdminName]
    FROM [dbo].[Employees] AS [Extent1]
    WHERE ([Extent1].[Discriminator] IN (N'Administrator',N'Employee')) AND ( EXISTS (SELECT 
        1 AS [C1]
        FROM [dbo].[Employees] AS [Extent2]
        WHERE ([Extent2].[Discriminator] = N'Administrator') AND ([Extent2].[Id] = [Extent1].[Id])
    ))

编辑 你最好使用 !(e is Administrator)

ctx.Employees.Where(e => !(e is Administrator)).ToList();

创建以下 SQL:

SELECT 
    [Extent1].[Discriminator] AS [Discriminator], 
    [Extent1].[Id] AS [Id], 
    [Extent1].[EmployeeRole] AS [EmployeeRole], 
    [Extent1].[IsAdmin] AS [IsAdmin], 
    [Extent1].[Age] AS [Age], 
    [Extent1].[AdminName] AS [AdminName]
    FROM [dbo].[Employees] AS [Extent1]
    WHERE ([Extent1].[Discriminator] IN (N'Administrator',N'Employee')) 
    AND ([Extent1].[Discriminator] <> N'Administrator')