关于DbSet和Discriminator

时间:2015-03-14 10:30:29

标签: c# asp.net-mvc-4

我想使用Discriminator属性过滤DbSet的行。为了解释更多,我有一个名为Employee的表,它包含Discriminator属性,用于指定Employee是简单的Employee还是Administrator。我想更改Employee-controller中的Index视图,以仅显示Employees而不显示Administrators。 这是当前的代码:

    //
    // 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")));
    }

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

以下是我的模型类:

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

1 个答案:

答案 0 :(得分:1)

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')