简体   繁体   English

SQL 到 LINQ 的内部连接转换和不同表上的过滤器

[英]SQL to LINQ conversion with inner join and where filters on different tables

What will the following query:以下查询会是什么:

select (UserRoles.RoleID, UserRoles.UserID) from UserRoles  
    inner Join Roles on Roles.RolesID = UserRoles.RoleID 
    where Roles.RoleName = 'Seller' AND UserRoles.UserID =1

look like in Entity framework?看起来像实体框架?

I tried this:我试过这个:

var check = from a in UserRole 
            join b in Role 
            on a.RoleID equals b.RoleID
            select new{RoleName ="seller"};

but it's wrong, could someone please guide me?但这是错误的,有人可以指导我吗?

The verbatim conversion of the query (after removing the parents in SELECT )查询的逐字转换(删除SELECT的父项后)

select UserRoles.RoleID, UserRoles.UserID
from UserRoles  
inner Join Roles on Roles.RolesID = UserRoles.RoleID 
where Roles.RoleName = 'Seller' AND UserRoles.UserID =1;

Would be the following in query syntax, against your DbContext called context (and I've assumed the default plural naming convention of DbSets:)将是查询语法中的以下内容,针对您的DbContext称为context (我假设 DbSets 的默认复数命名约定:)

var result = from a in context.UserRoles
             join b in context.Roles
             on a.RoleID equals b.RoleID
             where b.RoleName == "Seller" && a.UserId == 1
             select new {b.RoleID, a.UserID};

Where we join the tables and project out the two columns you wanted.我们加入表格并投影出您想要的两列。

However, if you've defined the navigation property UserRole.Role in your EF Model, explicit joining isn't required, and much simpler would be (I've switched to lambda syntax):但是,如果您已在 EF 模型中定义了导航属性UserRole.Role ,则不需要显式加入,而且会更简单(我已切换到 lambda 语法):

var result = context.UserRoles
   .Where(ur => ur.UserID == 1 && ur.Role.Name == "Seller")
   .Select(ur => new {ur.RoleID, ur.UserID});

Again, projecting out just the two columns into an anonymous class.同样,将两列投影到一个匿名类中。 If you omit the final Select statement entirely, you'll get the full UserRole entity instance.如果完全省略最后的Select语句,您将获得完整的UserRole实体实例。

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

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