3

我有一个客户表和一个地址表(customer_id、address_forename、address_surname、address_street、address_city、address_zip、address_storedtime),其中 customer_id 作为外键。

一个客户可以有多个地址。

现在我试图只使用 LINQ 获取最后输入的地址,如下所示,这应该允许我将地址放在一个字符串中并返回:代码:

var customerAddress = (from c in myDB.address
                       where (c.customer_id == customerId)
                       select new
                       {
                           c.customer_id,
                           c.address_forename,
                           c.address_surname,
                           c.address_street,
                           c.address_city,
                           c.address_zip,
                           c.address_storedtime
                       }).GroupBy(g => new
                       {
                           Customer = .customer_id,
                           Address = g.address_forename + " " + g.address_surname + " " + g.address_street + " " +        g.address_city + " " + g.address_zip 
                       }).Select(g => new
                       {
                           g.Key.Customer,
                           g.Key.Address,   
                           StoredTime = g.Max(x => x.address_storedtime)
                       }).Disinct();/*First();*/

string result = "";

foreach (var ad in customerAddress)
{
    if (ad.Address != null)
    {
        result = ad.Address;
    }
    break;
}

return result;

我为客户在数据库中的不同地址获得相同的地址字符串,而我试图只获得一个。

4

2 回答 2

2

由于您已经按客户 ID 进行过滤,因此不需要分组子句。您应该能够为客户降序排列结果并更简单地投影地址。

var customerAddress = (from c in myDB.address
                        where (c.customer_id == customerId)
                        orderby c.address_storedtime descending
                        select c.address_forename + " " + c.address_surname + " " + c.address_street + " " +        c.address_city + " " + c.address_zip)
                      .FirstOrDefault();
于 2012-10-05T13:29:50.803 回答
0

替换你foreach

var result =
    customerAdress.Any(ad => ad.Address != null) 
    ? customerAdress.Last(ad => ad.Address != null).Address
    : default(string);
于 2012-10-05T11:19:35.620 回答