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

hclinux 2011-08-24 05:34:22
在做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") (报错)

为什么会出现这种情况呢?还有报错的那个做法要怎么修改?请高手们帮忙解答啊,多谢了!
...全文
173 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
focolo 2012-09-07
  • 打赏
  • 举报
回复
3楼这个语句,性能问题??
q107770540 2011-08-25
  • 打赏
  • 举报
回复
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
};
hclinux 2011-08-25
  • 打赏
  • 举报
回复
按照“q107770540”第一种做法,是可以的,但是如果改成左连接又遇到问题了
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=(string)b.Element("id"),
bookname = (string)b.Element("bookname"),
publish = (string)b.Element("publish"),
price=(string)b.Element("price"),
booktype=t.typename
};

这样会报错,“未将对象引用到实例化”,请问如果要实现左连接要怎么改呢?
q107770540 2011-08-24
  • 打赏
  • 举报
回复
你的问题可尝试下边两种方法来解决:
1.

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

2.

var q = from t in data.booktype
from b in xe.Descendants("book")
where t.id == (int)b.Attribute("booktype")

8,497

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 LINQ
社区管理员
  • LINQ
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧