为什么DbSet不协调? [英] Why isn't DbSet covariant?

查看:120
本文介绍了为什么DbSet不协调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个工厂函数返回一个 DbSet(OfIItemType)。实际的返回类型将始终是一个实现 IItemType ,例如 DbSet(Of CategoryType)

I have a factory function to return a DbSet(Of IItemType). The actual return type will always be an implementation IItemType, for example DbSet(Of CategoryType).

我以为泛型支持协方差,这种方法可以正常工作,但是当我尝试运行我的代码时,我得到一个例外:

I thought covariance is supported in generics and this method would work fine, but I get an exception when I try to run my code:

无法转换类型为'System.Data.Entity.DbSet 1 [CategoryType]'的对象键入'System.Data.Entity.DbSet 1 [IItemType]'。

Unable to cast object of type 'System.Data.Entity.DbSet1[CategoryType]' to type 'System.Data.Entity.DbSet1[IItemType]'.


推荐答案

看起来他们可以是协变的。但是有一个差异​​主机针对查询提供程序的内存中编程和编程。

It looks like they could be covariant. But there is a host of differences between in-memory programming and programming against a query provider.

对于实体框架来实现数据存储中的对象,它需要其精确类型以及从数据库列到类型属性的映射。一个界面可以表示任何类型,EF并不能够自己选择一个合适的实现。在未来的版本中可能会支持接口。

For Entity Framework to materialize an object from the data store it requires its exact type and the mapping from database columns to the type's properties. An interface can represent any type and EF is not (yet) able to pick a suitable implementation itself. Maybe support for interfaces will be featured in future releases.

同样的情况也适用于在EF查询中将接口投放到一个接口(我刚刚添加到我的差异列表中的情况) )。

The same applies to casting entities to an interface in an EF query (a case I just added to my list of differences).

这篇关于为什么DbSet不协调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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