如何将此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
答案 0 :(得分:11)
非常相似:
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
};
上面的项目是一个具有你想要的属性的匿名类 - 如果你的模型中有一个等效的POCO类,你应该投射到那个,如果不是在很多情况下你可能应该创建一个。
答案 1 :(得分:2)
来自@BrokenGlass的解决方案非常好。 但是,如果您有1..many关系,则很少需要在LINQ中使用join运算符。在这个例子中,如果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
};
这也可以使用表达式链语法编写:
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)
答案 2 :(得分:-1)
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();