嵌套的linq-to-sql查询

时间:2010-05-17 12:45:11

标签: linq-to-sql nested

var result = (
    from contact in db.Contacts                             
    join user in db.Users on contact.CreatedByUserID equals user.UserID
    orderby contact.ContactID descending
    select new ContactListView
    {
        ContactID = contact.ContactID,
        FirstName = contact.FirstName,
        LastName = contact.LastName,
        Company = (
            from field in contact.XmlFields.Descendants("Company")
            select field.Value).SingleOrDefault().ToString()
    }).Take(10);

Here我描述了数据库表的外观。因此,contacts表有一个xml类型的字段。在该字段中存储公司文件名,我需要阅读它。我用这种方式试了一下:

Company = (
    from field in contact.XmlFields.Descendants("Company")
    select field.Value).SingleOrDefault().ToString()

但我收到以下错误:

  

成员访问'System.String Value'   'System.Xml.Linq.XElement'不合法   在类型上   “System.Collections.Generic.IEnumerable`1 [System.Xml.Linq.XElement]。

对此有何解决方案?

提前致谢,
ILE

1 个答案:

答案 0 :(得分:3)

这里的问题是LINQ to SQL正在尝试将Descendants扩展方法和XElement.Value转换为SQL,但它当然会失败。您将不得不使用LINQ to Objects进行最后一次转换。这可行:

var temp = (
    from contact in db.Contacts                             
    join user in db.Users on contact.CreatedByUserID equals user.UserID
    orderby contact.ContactID descending
    select new
    {
        contact.ContactID, contact.FirstName, contact.LastName, contact.XmlFields
    })
    .Take(10);

var tempArray = temp.ToArray();

IEnumerable<ContactListView> result =
    from contact in tempArray
    let company =
        (from field in contact.XmlFields.Descendants("Company")
         select field.Value).SingleOrDefault()
    select new ContactListView()
    {
        ContactID = contact.ContactID,
        FirstName = contact.FirstName,
        LastName = contact.LastName,
        Company = company == null ? null : company.ToString()
    }).Take(10);