专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > LINQ

LINQ TO SQL AND LINQ TO XML联合查询遇到的有关问题

发布时间:2011-06-24 21:53:56 文章来源:www.iduyao.cn 采编人员:星星草
LINQ TO SQL AND LINQ TO XML联合查询遇到的问题
在做LINQ TO SQL AND LINQ TO XML联合查询时遇到一个奇怪的问题,情况如下

这样做是没问题的

  BookDataContext data = new BookDataContext();
  XElement xe = XElement.Load(Server.MapPath("myxml.xml"));
  var q=from b in xe.Descendants("book")
  join t in data.booktype on (int)b.Attribute("booktype") equals t.id
  select new { 
  id=(string)b.Element("id"),
  bookname = (string)b.Element("bookname"),
  publish = (string)b.Element("publish"),
  price=(string)b.Element("price"),
  booktype=t.typename
  };
  foreach (var qq in q)
  {
  Response.Write(qq.id + "--" + qq.bookname + "--" + qq.price + "--" + qq.publish + "--" + qq.booktype + "<br>");
  }

但是对调一下位置就出现问题了(报错为 :不能在查询运算符(Contains() 运算符除外)的 LINQ to SQL 实现中使用本地序列。 )

  BookDataContext data = new BookDataContext();
  XElement xe = XElement.Load(Server.MapPath("myxml.xml"));
  var q = from t in data.booktype
  join b in xe.Descendants("book") on t.id equals (int)b.Attribute("booktype")
  select new
  {
  id = (string)b.Element("id"),
  bookname = (string)b.Element("bookname"),
  publish = (string)b.Element("publish"),
  price = (string)b.Element("price"),
  booktype = t.typename
  };
  foreach (var qq in q)
  {
  Response.Write(qq.id + "--" + qq.bookname + "--" + qq.price + "--" + qq.publish + "--" + qq.booktype + "<br>");
  }

真是奇怪了
  var q=from b in xe.Descendants("book")
  join t in data.booktype on (int)b.Attribute("booktype") equals t.id (没问题)

  var q = from t in data.booktype
  join b in xe.Descendants("book") on t.id equals (int)b.Attribute("booktype") (报错)

为什么会出现这种情况呢?还有报错的那个做法要怎么修改?请高手们帮忙解答啊,多谢了!


------解决方案--------------------
var q = from t in data.booktype.ToList()
join b in xe.Descendants("book") on t.id equals (int)b.Attribute("booktype") into bb
from b in bb.DefaultIfEmpty()
select new {
id=b==null?"0":(string)b.Element("id"),
bookname =b==null?"": (string)b.Element("bookname"),
publish =b==null?"": (string)b.Element("publish"),
price=b==null?"":(string)b.Element("price"),
booktype=t.typename
};
友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: