代码之家  ›  专栏  ›  技术社区  ›  ilija veselica

嵌套的LINQ to SQL查询

  •  3
  • ilija veselica  · 技术社区  · 15 年前
    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[系统.xml.Linq.Xelement]。

    有什么解决办法吗?

    事先谢谢,
    伊利

    1 回复  |  直到 15 年前
        1
  •  3
  •   Steven    15 年前

    这里的问题是Linq to SQL正在尝试转换 Descendants 扩展方法和 XElement.Value 到SQL,但它当然失败了。您必须使用linq to对象进行最后一次转换。这是可行的:

    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);