如何将此查询转换为实体框架查询?
select Price,
(
select Cost.Title
from Cost
where Cost.CostID= CostItem.CostID
) as nameCost
from CostItem
where ItemID= 11
答案 0 :(得分:1)
您的查询也可以使用LEFT JOIN
:
SELECT
ci.Price,
NameCost = c.Title
FROM CostItem ci
LEFT JOIN Cost c
ON c.CostID = ci.CostID
WHERE ci.ItemID = 11
使用C#将其转换为Linq,您得到:
var t =
from ci in CostItem
join c in Cost on ci.CostID equals c.CostID into lc
from c in lc.DefaultIfEmpty()
where ci.ItemID == 11
select new {
Price = ci.Price,
NameCost = c.Title
};
答案 1 :(得分:1)
var result = dbContext.CostItems
.Where(item => item.ItemId == 11)
.Select(item => new { Price = item.Price, nameCose = item.Cost.Title })
确保您在实体对象中正确设置了关系