【发布时间】:2011-11-26 01:42:27
【问题描述】:
我对 LINQ 相当陌生,无法解决一些行为不一致的问题。任何知识渊博的输入将不胜感激。我在 SO 和其他地方看到了类似的问题,但它们似乎没有帮助。
我有一个非常简单的设置 - 一个公司表和一个地址表。每个公司可以有 0 个或多个地址,如果 > 0,则必须指定一个作为主要地址。我正在尝试处理有 0 个地址的情况,使用外部连接并相应地更改 select 语句。
请注意,我目前将输出直接绑定到 GridView,因此我希望将所有处理都保留在查询中。
以下可以工作
IQueryable query =
from comp in context.Companies
join addr in context.Addresses on comp.CompanyID equals addr.CompanyID into outer // outer join companies to addresses table to include companies with no address
from addr in outer.DefaultIfEmpty()
where (addr.IsMain == null ? true : addr.IsMain) == true // if a company has no address ensure it is not ruled out by the IsMain condition - default to true if null
select new {
comp.CompanyID,
comp.Name,
AddressID = (addr.AddressID == null ? -1 : addr.AddressID), // use -1 to represent a company that has no addresses
MainAddress = String.Format("{0}, {1}, {2} {3} ({4})", addr.Address1, addr.City, addr.Region, addr.PostalCode, addr.Country)
};
但这会将 GridView 中的空地址显示为“, , ()”
所以我将 MainAddress 字段更新为
MainAddress = (addr.AddressID == null ? "" : String.Format("{0}, {1}, {2} {3} ({4})", addr.Address1, addr.City, addr.Region, addr.PostalCode, addr.Country))
现在我收到了 Could not translate expression 错误和一堆自动生成的错误代码,这对我来说意义不大。
我添加到 MainAddress 的条件与 AddressID 上的工作条件没有什么不同,所以谁能告诉我这里发生了什么?
非常感谢任何帮助。
【问题讨论】:
-
可能想在问题中添加“spewey 自动生成的代码”。
标签: asp.net linq linq-to-sql