开发者

Using Entity Framework how do I filter by a foreign key using multiple enumeration values?

Two tables (MainTable and EventType). EventType is represented in code as an enumeration and is foreign ke开发者_运维技巧yed in the database so that it looks like;

Public enum EventTypeId As Integer
    Blah = 1
    Blurgh = 2
    Whoo = 3
End Enum

I can run the following query fine;

From M in dbx.MainTable Where M.EventType.EventTypeId = 1

But I can't do this (psuedo code);

From M in dbx.MainTable Where M.EventType.EventTypeId.Contains(EventTypeId.Blah,EventTypeId.Whoo)

The 2nd approach is more readable and maintainable as it links to the enum, but I can't find a construct in EF that allows me to do this.

This is the current version of EF, not .Net 4.0.

In summary, what I want to do in SQL is easy, it just needs to be in EF;

Select * From MainTable Where EventTypeId In (1,3);


If you look at what you want:

In summary, what I want to do in SQL is easy, it just needs to be in EF;

Select * From MainTable Where EventTypeId In (1,3);

you should explain it as: EventTypeId should be part of (1,3). The equivalent for this is: (1,3) contains EventTypeId

What you are trying is:

But I can't do this (psuedo code)

From M in dbx.MainTable Where M.EventType.EventTypeId.Contains(EventTypeId.Blah,EventTypeId.Whoo)

But then you are trying: EventTypeId contains (1,3)

The solution is todo what you actually want in SQL in the contains syntax, but turn it around: you should look for (1,3) contains EventTypeId

So create a list of int with the specific EventType id's you are looking for. And then filter all records where EventTypeId is part of the list of id's

List<int> eventTypeIds = new List<int>();
eventTypeIds.Add((int)EventTypeId.Blah);
eventTypeIds.Add((int)EventTypeId.Whoo);

From M in dbx.MainTable Where eventTypeIds.Contains(M.EventTypeId)


Never tried something similar, but have you tested if it works by casting your enumerations to integers, as the following?

(int)EventTypeID.Blah

Sorry, can't help much more than this without trying for myself, what is not possible right now.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜