EntityFramework 投射问题
我正在使用 LinqKit 中的 PredicateBuilder 构建查询。 它很棒并且正是我想要的。
为了使我的代码更具可重用性(表和视图),我创建了一个通用谓词构建器类:
public class LocalPredicateBuilder<T> where T : IResort
...
var predicate = PredicateBuilder.True<T>(
它公开了 BuildPredicate 方法。我可以这样使用它:
var predicate = new LocalPredicateBuilder<Resort>().BuildPredicate();
var resorts = _entities.Resorts.Where(predicate).ToList();
但是,当我尝试这样做时,我收到此运行时错误(顺便说一句,实体对象实现了 IResort): 无法将类型“ConsoleApplication1.Entities.Resort”转换为类型“ConsoleApplication1.Entities.IResort”。 LINQ to Entities 仅支持转换实体数据模型基元类型
我尝试了转换(不起作用):
var rlist = eq.Cast<Resort>().ToList();
还有其他方法可以解决此转换问题吗?
更新
没有太多运气让谓词使用接口工作..所以我通过使用 POCO 解决了我的问题。
I am building my query using PredicateBuilder from LinqKit.
it is great and does exactly what i am looking for.
To make my code more reusable (tables and views) i created a generic predicate builder class:
public class LocalPredicateBuilder<T> where T : IResort
...
var predicate = PredicateBuilder.True<T>(
which exposes BuildPredicate method. I can use it like this:
var predicate = new LocalPredicateBuilder<Resort>().BuildPredicate();
var resorts = _entities.Resorts.Where(predicate).ToList();
however when i try to do this, i get this runtime error (btw entity objects implement IResort):
Unable to cast the type 'ConsoleApplication1.Entities.Resort' to type 'ConsoleApplication1.Entities.IResort'. LINQ to Entities only supports casting Entity Data Model primitive types
i tried casting (didn't work):
var rlist = eq.Cast<Resort>().ToList();
Any other way i can get around this casting issue?
UPDATE
not having much luck getting predicates to work using interfaces.. so i solved my problem by going with POCOs.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
嗯,错误是准确的。您无法在 L2E 查询中执行此操作,因为您的接口 (
IReport
) 不是实体模型的一部分,因此无法转换为 SQL。您必须使用实体类型,而不是接口。Well, the error is accurate. You can't do that in an L2E query, because your interface (
IReport
) is not part of your entity model and hence can't be converted to SQL. You have to use an entity type, not an interface for that.只需为实体框架对象创建一个分部类并使其实现接口。
另一种方法是创建所需类型的列表
,然后在 linq 数据集上为每个类型执行一个列表,并将项目添加到集合中。
这个问题是因为.net不知道如何投射而引起的
将
List
放入List
just create a partial class for the entity frameowrk object and make that implement the interface.
the other way would be to create a list of the type you want
then do a for each on the linq dataset and add the items to the collection.
the problem is caused because .net doesnt know how to cast
List<ISomething>
into aList<Something>