关于DbSet和鉴别器

用户名

我想使用Discriminator属性过滤DbSet的行。为了进一步说明,我有一个名为Employee的表,它包含Discriminator属性,用于指定Employee是简单的Employee还是Administrator。我想在Employee-controller中更改Index视图,以仅显示雇员,而不显示管理员。这是当前代码:

    //
    // 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
{
}
米哈尔·西尚(Michal Ciechan)
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')

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章