我会先声明,我正在使用动态数据上的 linq 做一些非常可怕的事情。 但是我不明白为什么这个查询编译失败:
错误 1 属性 '<>h__TransparentIdentifier0' 不能与类型参数一起使用
public class Program { public static void Main(string[] args) { var docs = new dynamic[0]; var q = from doc in docs where doc["@metadata"]["Raven-Entity-Name"] == "Cases" where doc.AssociatedEntities != null from entity in doc.AssociatedEntities where entity.Tags != null // COMPILER ERROR HERE from tag in entity.Tags where tag.ReferencedAggregate != null select new {tag.ReferencedAggregate.Id, doc.__document_id}; } } public static class LinqOnDynamic { private static IEnumerable<dynamic> Select(this object self) { if (self == null) yield break; if (self is IEnumerable == false || self is string) throw new InvalidOperationException("Attempted to enumerate over " + self.GetType().Name); foreach (var item in ((IEnumerable) self)) { yield return item; } } public static IEnumerable<dynamic> SelectMany(this object source, Func<dynamic, int, IEnumerable<dynamic>> collectionSelector, Func<dynamic, dynamic, dynamic> resultSelector) { return Enumerable.SelectMany(Select(source), collectionSelector, resultSelector); } public static IEnumerable<dynamic> SelectMany(this object source, Func<dynamic, IEnumerable<dynamic>> collectionSelector, Func<dynamic, dynamic, dynamic> resultSelector) { return Enumerable.SelectMany(Select(source), collectionSelector, resultSelector); } public static IEnumerable<dynamic> SelectMany(this object source, Func<object, IEnumerable<dynamic>> selector) { return Select(source).SelectMany<object, object>(selector); } public static IEnumerable<dynamic> SelectMany(this object source, Func<object, int, IEnumerable<dynamic>> selector) { return Select(source).SelectMany<object, object>(selector); } }
雪上加霜的是,以下工作:
var docs = new dynamic[0]; var q = from doc in docs where doc["@metadata"]["Raven-Entity-Name"] == "Cases" where doc.AssociatedEntities != null from entity in doc.AssociatedEntities where entity.Tags != null from tag in entity.Tags select new { tag.ReferencedAggregate.Id, doc.__document_id };
只有当我添加:
其中 tag.ReferencedAggregate != null
我在两行之前得到一个错误:
where entity.Tags != null//此处编译器错误
不知道发生了什么
最佳答案
如果我尝试将您的调用转换为:
var q = from doc in docs.Where(doc => doc["@metadata"]["Raven-Entity-Name"] == "Cases" || doc.AssociatedEntities != null)
from entity in doc.AssociatedEntities.Where(entity => entity.Tags != null)
我得到一个不同的编译器错误,它可能揭示了正在发生的事情:
“如果不首先将 lambda 表达式转换为委托(delegate)或表达式树类型,则不能将其用作动态分派(dispatch)操作的参数”
所以我猜你必须重载 Where 运算符。
关于c# - 动态+linq编译报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3444786/