[英]SQL INNER JOIN with WHERE clause to LINQ format
How would I convert this sql query to LINQ? 我如何将此SQL查询转换为LINQ?
SELECT company.ticker, company.primary_analyst,
personnel.last_name, company.research_associate,
company.secondary_associate, company.coverage_status
FROM company
INNER JOIN personnel ON company.primary_analyst = personnel.dpinitials
WHERE personnel.last_name='marley' AND company.associate='ml'
ORDER BY company.coverage_status
It's pretty similar: 它非常相似:
var results = from c in company
join p in personnel on c.primary_analyst equals p.dpinitals
where p.last_name == 'marley' and c.associate == 'ml'
orderby c.coverage_status asc
select new
{
c.ticker, c.primary_analyst, p.last_name, c.research_associate,
c.secondary_associate, c.coverage_status
};
Above projects to an anonymous class with the properties you want - if you have an equivalent POCO class in your model you should project to that, if not in many cases you probably should create one. 上面的项目是一个具有你想要的属性的匿名类 - 如果你的模型中有一个等效的POCO类,你应该投射到那个,如果不是在很多情况下你可能应该创建一个。
The solution from @BrokenGlass is perfectly fine. @BrokenGlass的解决方案非常好。 However, if you have a 1..many relationship it is rarely necessary to use the join operator in LINQ. 但是,如果您有1..many关系,则很少需要在LINQ中使用join运算符。 In this example, if company->personell was 1..many, I would write the query like this: 在这个例子中,如果company-> personell是1..many,我会写这样的查询:
var results = from c in company
where c.associate == "ml"
from p in c.personnel
where p.last_name == "marley"
orderby c.coverage_status asc
select new
{
c.ticker,
c.primary_analyst,
p.last_name,
c.research_associate,
c.secondary_associate,
c.coverage_status
};
This can also be written using the expression chain syntax: 这也可以使用表达式链语法编写:
var results = company.Where(c => c.associate == "ml")
.SelectMany(c => c.personnel, (c, p) => new
{
c.ticker,
c.primary_analyst,
p.last_name,
c.research_associate,
c.secondary_associate,
c.coverage_status
})
.Where(x => x.last_name == "marley")
.OrderBy(x => x.coverage_status)
var list = (from u in db.Users
join c in db.Customers on u.CustomerId equals c.CustomerId
where u.Username == username
select new {u.UserId, u.CustomerId, u.ClientId, u.RoleId, u.Username, u.Email, u.Password, u.Salt, u.Hint1, u.Hint2, u.Hint3, u.Locked, u.Active,c.ProfilePic}).First();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.