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