开发者

No Way to Query Connecting Table

Let's say I have two tables, A and B with a many-to-many relationship using the conn开发者_如何学Goecting table AB.

Table A

AID int

Table B

BID int

Table AB

AID int
BID int

My task is to find all the rows in AB where AB.AID = 2 using linq to entity framework 4.

Part of the problem is that the AB table is not included in the entities model. Only A and B are included with a many-to-many relationship. But since I don't need the information from B, it would be a waste to involve a many-to-many join for this task.

This is trivial using SQL but I don't see how to do it using linq to Entity Framework.


In my experience, the best way around this issue is to add a primary key to the AB table such as ABID so that it does appear in your context.

That way your query would look something like this:

var q = from ab in context.AB
        where ab.BID == 2
        select ab;

I understand this solution is not completely ideal, but it should work.


var q = from a in Context.TableA
        where a.TableB != null
        select new 
        {
            AID = a.AID,
            BID = a.TableB.BID
        };
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜