2010-05-17 95 views
3
​​

Here我描述了我的数据库表什么样子。所以,contacts表有一个字段是xml类型。在该字段中存储公司文件名,我需要阅读它。我尝试了用这种方式:嵌套的LINQ到SQL查询

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

,但我得到以下错误:

Member access 'System.String Value' of 'System.Xml.Linq.XElement' not legal on type 'System.Collections.Generic.IEnumerable`1[System.Xml.Linq.XElement].

这个任何解决方案?

由于提前,

回答

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

是的,就是这样。我从来没有想过独自一人:)虽然,这不是真正实用的解决方案,但重要的是它的工作原理。谢谢 ;) – 2010-05-18 07:40:58