2

I have a field in my database table that use to store an enumeration value, e.g.:

create table MyTable (
  ...
  Status tinyint not null,
  ...
)

and in my C# class I have

public enum TStatus : byte {
  Pending = 1      
  Active = 2,
  Inactive = 3,
}

public TStatus MyStatus {
  get { return (TStatus)Status; }
  set { Status = (byte)value; }
}

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

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?

Shaul Behr
  • 36,951
  • 69
  • 249
  • 387

2 Answers2

7

Check out this link:

http://dotnet.org.za/hiltong/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:

[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

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
BFree
  • 102,548
  • 21
  • 159
  • 201
  • Same post I've been to several times (every time I forget how to do this). Also first time I actually got to see the global qualifier at work. –  Jun 17 '09 at 15:54
  • Perfect answer - thanks! Even better that it comes from a South African blog! Voerspoed! – Shaul Behr Jun 17 '09 at 15:59
0

Don't have a compiler handy, but I think if you cast your enum to an int, it will work. So try:

var q = MyDataContext.GetTable().Where(t => t.MyStatus == (int)TStatus.Active);

Ciaran O'Neill
  • 2,572
  • 6
  • 34
  • 40