我需要帮助转换的一些SQL选择到LINQ转换SQL到LINQ
原来这里是SQL:
Select Top 1 IsNull(ct.Template, t.Template) as Template
From Template t
Left Outer Join ClientTemplate ct On t.TemplateTypeId = ct.TemplateTypeId And ct.ClientId = 149
Where t.TemplateTypeId = (Select TemplateTypeId From QuoteType Where QuoteTypeId = 7)
Order By t.Version DESC, ct.Version DESC
我使用实体框架,并有QuoteTypes,ClientTemplates和模板实体。
上述SQL从客户端149的ClientTemplate表中获取模板(在实际代码中使用变量)用于特定的QuoteType。如果CLientTemplate表中没有条目,那么它会从相同QuoteType的主Template表中返回Template!
我的想法是首先查询QuoteType,然后查询ClientTemplate表,看看是否存在,如果不是查询模板表。问题是这会导致三个查询,但我相信它可以一举完成!?
任何人都可以为我编写LINQ吗?
这里是我的烂摊子至今:
QuoteType quoteType = (from qt in this.entities.QuoteTypes where qt.QuoteTypeID == this.SelectedNewQuoteTypeID select qt).First();
if (quoteType != null && quoteType.TemplateTypeID.HasValue)
{
int quoteTypeTemplateTypeID = (int)quoteType.TemplateTypeID;
var query = (from t in this.entities.Templates
join ct in this.entities.ClientTemplates on t.TemplateTypeID equals ct.TemplateTypeID
into a
from b in a.DefaultIfEmpty(new ClientTemplate())
where t.TemplateTypeID == quoteTypeTemplateTypeID
orderby t.Version descending
select new
{
T1 = t.Template1,
T2 = b.Template
}).First();
// Check the query to see if T1 and T2 are null and use whichever one isn't!
// TODO !!!
}
else
{
return string.Empty;
}
我有点放弃了,一旦我得到的远远张贴了这个!我的例子仍然有两个查询,并且不根据客户端ID进行选择。它在客户端模板表上也没有第二顺序。
我已经继承了原始的SQL语句,所以也许问题在于被写得很糟糕!
过你......
您也可以在您的数据库中创建一个视图或存储过程来封装此SQL代码,然后通过LINQ调用它。 – RBarryYoung 2014-10-09 19:11:42
仅供参考,SQL查询对我来说看起来很好。尽管如果您将WHERE子句中的子查询更改为JOIN,但对LINQ来说可能更容易(不确定)。 – RBarryYoung 2014-10-09 19:13:35
使用导航属性代替连接。如果您需要帮助,请显示您的实体课程,包括这些属性。 – 2014-10-09 20:04:42