为什么不能将LINQ to XML与LINQ to SQL相结合? [英] Why isn't it possible to combine LINQ to XML with LINQ to SQL?

查看:83
本文介绍了为什么不能将LINQ to XML与LINQ to SQL相结合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码:

var xml = XDocument.Load(filePath);
var taxReturns = (from t in xml.Descendants("aangiftes").Elements()
    where t.Name == "ib"
    select new Domain.TaxReturn
    {
        FiscalNumber = t.Attribute("sofinr").Value,
        Guid = Guid.Parse(t.Attribute("guid").Value),
        LastFormOpen = t.Attribute("lastformview").Value,
        Name = string.Empty, 
        TaxYear = t.GetAttributeValue<short>("belastingjaar"),
        TaxForm =  unitOfWork.TaxForms.FirstOrDefault(tf => tf.Code == t.Attribute("biljetsoort").Value),
    }).ToArray();

运行此代码时,出现此异常:

When I run this code, I get this exception:

LINQ to Entities无法识别方法System.Xml.Linq.XAttribute Attribute(System.Xml.Linq.XName)-方法,并且该方法无法转换为商店表达式

LINQ to Entities does not recognize the method System.Xml.Linq.XAttribute Attribute(System.Xml.Linq.XName)-method, and this method cannot be translated into a store expression

但是,当我将此行提取到方法中时,它可以正常工作.

However, when I extract this line into a method, it works fine.

有人可以解释这种行为吗?我不了解这种行为:/

Could someone explain this behavior? I don't understand this behavior :/

推荐答案

这是因为LINQ尝试将Domain.TaxReturn {...}内部的代码编译为SQL. SQL中没有用于XElement.Attribute(...)的相应API,因此它将失败.

This is because LINQ tries to compile the code inside Domain.TaxReturn {...} into SQL. There is no corresponding API in SQL for XElement.Attribute(...) so it fails.

尝试将依赖XElement的代码移到Domain.TaxReturn {...}
之外 像这样:

Try to move the XElement dependent code outside of Domain.TaxReturn {...}
Like this:

var xml = XDocument.Load(filePath);
var taxReturns = (from t in xml.Descendants("aangiftes").Elements()
    where t.Name == "ib"
    let sofinr = t.Attribute("sofinr").Value
    let guid = Guid.Parse(t.Attribute("guid").Value)
    let lastformview = t.Attribute("lastformview").Value
    let belastingjaar = t.GetAttributeValue<short>("belastingjaar")
    let biljetsoort = t.Attribute("biljetsoort").Value
    select new Domain.TaxReturn
    {
        FiscalNumber = sofinr ,
        Guid = guid,
        LastFormOpen = lastformview,
        Name = string.Empty, 
        TaxYear = belastingjaar,
        TaxForm = unitOfWork.TaxForms.Single(tf => tf.Code == biljetsoort),
    }).ToArray();

(未经测试)

此外,您可能想使用Enumerable.Single而不是Enumerable.FirstOrDefault,还是null是有效的情况?

Also, you probably want to use Enumerable.Single instead of Enumerable.FirstOrDefault, or is null a valid case?

这篇关于为什么不能将LINQ to XML与LINQ to SQL相结合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆