简体   繁体   English

如何在实体SQL中引用枚举类型

[英]How to reference enum type in entity sql

I have the following (simplified) Entity SQL query: 我有以下(简化的)实体SQL查询:

SELECT VALUE a
FROM Customers AS a
WHERE a.Status NOT IN { 2, 3 }

The Status property is an enumeration type, call it CustomerStatus . Status属性是枚举类型,称为CustomerStatus The enumeration is defined in the EDMX file. 枚举在EDMX文件中定义。

As it is, this query doesn't work, throwing an exception to the effect that CustomerStatus is incompatible with Int32 (its underlying type is int). 实际上,此查询不起作用,抛出一个异常,即CustomerStatus与Int32不兼容(其基础类型 int)。 However, I couldn't find a way to define a list of CustomerStatus values for the IN {} clause, no matter what namespace I prefixed to the enumeration name. 但是,无论我为枚举名称添加了什么名称空间,我都无法找到一种方法来为IN {}子句定义CustomerStatus值的列表。 For example, 例如,

SELECT VALUE a
FROM Customers AS a
WHERE a.Status NOT IN { MyModelEntities.CustomerStatus.Reject, MyModelEntities.CustomerStatus.Accept }

did not work, throwing an exception saying it could not find MyModelEntities.CustomerStatus in the container, or some such. 不能正常工作,抛出异常说它在容器中找不到MyModelEntities.CustomerStatus或类似的东西。

Eventually I resorted to casting the Status to int, such as 最终,我求助于将Status强制转换为int,例如

SELECT VALUE a
FROM Customers AS a
WHERE CAST(a.Status AS System.Int32) NOT IN { 2, 3 }

but I was hoping for a more elegant solution. 但我希望有一个更优雅的解决方案。

Oooh, you are writing Entity SQL directly. 噢,您正在直接编写实体SQL。 I see... Any reason you aren't using DbSet instead of writing Entity SQL by hand? 我明白了。有什么理由不使用DbSet而不是手工编写Entity SQL? Could always do 总是可以做

var statuses = new [] { Status.A, Status.B };
var query = context.SomeTable.Where(a => !statuses.Contains(a.Status)).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM