日期:2014-05-20  浏览次数:20789 次

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