简体   繁体   English

我如何在实体框架中执行此操作(多个位置或加入)?

[英]How do I do this in Entity Framework (multiple where's or Join)?

I have 2 tables that have a relation ship to each other 我有2个表彼此相关联

Table A has 1 to many relationship with table B, so this creates a navigation property into each. 表A与表B具有1对多的关系,因此这会为每个表创建一个导航属性。

Now I need to check a value from Table A (userName) and I need to check a value from table B (ClubId). 现在我需要检查表A(userName)中的值,我需要检查表B(ClubId)中的值。

So in my mind it would be something like 所以在我看来它会是这样的

Join the tables together
Where A.userName == "bob" &&
where B.clubId == "Car"

// return the count.

but now I know with Entity stuff it should make joins less common so I am wondering if I can do it with a join then. 但现在我知道实体的东西它应该使连接不太常见,所以我想知道我是否可以通过连接来实现。

I tried this 我试过这个

int count = Entity.TableA.where(a => a.userName == "bob" && a.TableB.where(i => i.ClubId == "Car")).Count();

so this does not work since it won't return the right type(the 2nd where). 所以这不起作用,因为它不会返回正确的类型(第二个在哪里)。 This is just how I thought along the lines how I would expect it to be done would work. 这就是我的想法,我希望它能够完成的工作方式。

So how should it look? 那它应该怎么样?

PS PS

I rather have an example done in the Linq method queries like I did above. 我宁愿在Linq方法查询中完成一个例子,就像我上面做的那样。

Assuming your EF model has the relationship between Users and Clubs could do something like this: 假设您的EF模型具有用户和俱乐部之间的关系,可以执行以下操作:

var usersNamedBobInCarClub = 
             from A in User
             from B in A.Clubs
             where A.userName == "bob" &&
                   B.clubId == "Car"
             select A;

If you want return elements of both Users and Clubs have a look at joins within the query. 如果您希望用户和俱乐部的返回元素查看查询中的联接。

Filtering TableA before your join is probably more efficient: 在加入之前过滤TableA可能更有效:

var clubs = from a in Entity.TableA
            where a.userName == "bob"
            from b in a.TableB
            where b.clubId == "Car"
            select b;

var count = clubs.Count();

You don't have to use two variables, it's just my preference here for clarity. 您不必使用两个变量,为了清楚起见,这只是我的偏好。

Or in method syntax you can simplify a bit: 或者在方法语法中,您可以简化一下:

var count = Entity.TableA.Where(a => a.userName == "bob")
                         .SelectMany(a => a.TableB)
                         .Count(b => b.clubId == "Car");

However, I'm not certain EF understands those particular expressions. 但是,我不确定EF是否了解这些特定的表达方式。 If not, the compiler would translate the above query like this: 如果没有,编译器将翻译上述查询,如下所示:

var count = Entity.TableA.Where(a => a.userName == "bob")
                         .SelectMany(a => a.TableB, (a,b) => new { a, b })
                         .Where(x => x.b.clubId == "Car")
                         .Count();

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

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