问题描述
我的数据库表中有一个字段用于存储枚举值,例如:
I have a field in my database table that use to store an enumeration value, e.g.:
create table MyTable ( ... Status tinyint not null, ... )
在我的 C# 类中
public enum TStatus : byte { Pending = 1 Active = 2, Inactive = 3, } public TStatus MyStatus { get { return (TStatus)Status; } set { Status = (byte)value; } }
现在我想编写一个使用 MyTable 的 MyStatus 属性的 Linq 查询,例如
now I want to write a Linq query that uses the MyStatus property of MyTable e.g.
var q = MyDataContext.GetTable<MyTable>().Where(t => t.MyStatus == TStatus.Active);
当然,Linq 不知道如何将 MyStatus 解释为 SQL.我需要对 MyStatus 做什么才能让它在 LinqToSQL 中工作?
but of course, Linq doesn't know how to interpret MyStatus as SQL. What do I need to do to MyStatus in order for it to work in LinqToSQL?
推荐答案
查看此链接:
http://dotnet.org.za/hitong/archive/2008/08/06/using-enums-with-linq-to-sql.aspx
当链接失效时——至少对我来说这个链接失效了——这是重要的部分:
As links die - and at least for me this one did die - here is the important part:
[将列添加到实体时] 默认情况下,类型将显示为int (System.Int32)",但您可以将其更改为枚举的完全限定类型(在我的情况下,ConsoleApplication1.CustomerType).但是,为了完全定位它,您必须添加全局标识符,如下所示: global::ConsoleApplication1.CustomerType ,因此将其按原样(但与您的命名空间等效)输入文本框
[When adding the column to the entity] by default, the Type will come up as an "int (System.Int32)", but you can change it to the fully-qualified type of the enum (in my case, ConsoleApplication1.CustomerType). BUT, in order to locate it fully, you have to add the global identifier, as follows: global::ConsoleApplication1.CustomerType , so type that as is (but the equivalent for your namespace) into the textbox