实体框架:对象集和它的(仿制药)的方差 [英] Entity Framework: ObjectSet and its (generics) variance

查看:161
本文介绍了实体框架:对象集和它的(仿制药)的方差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用:的EntityFramework + POCO

I use: EntityFramework + POCO

下面是一点:

public interface IBaseType
{
    int Id { get; set; }
}

public class BaseType : IBaseType
{
    public virtual int Id { get; set; }
}

public class DerivedType : BaseType
{
}

问题:

public class EntityFetcher<T> where T : BaseType
{
    public object GetById(int id)
    {
        ObjectSet<T> objectSet = (ObjectSet<T>)GetTheObjectSet(typeof(T)); 

        return objectSet.SingleOrDefault((o) => o.Id == id);
    }
}

如果 T BASETYPE 这一切完美的作品,但是: 现在的问题是,在的EntityFramework当一个类继承了另一个他们共享对象集,因此,如果 T DerivedType GetTheObjectSet 返回对象集&LT;基本类型&GT; ,从而无法转换为对象集&LT; D​​erivedType&GT;

If T is BaseType this all works perfectly, but: The problem is that in EntityFramework when one class inherits another they share the ObjectSet and, therefore, if T is DerivedType then the GetTheObjectSet returns ObjectSet<BaseType>, which cannot be cast to ObjectSet<DerivedType>.

有没有办法实际施放此这件事情或以某种方式否则执行的SingleOrDefault ?可那些东西用定投的 IObjectSet&LT;&GT; IBaseType

Is there a way to actually cast this this thing or somehow else execute the SingleOrDefault? Can those things be cast using the IObjectSet<> and IBaseType?

推荐答案

这个问题的答案铸钢问题如下:

The answer to this casting problem was as follows:

public T GetById(int id)
{
    // The line that throws InvalidCast with T = DerivedType
    //ObjectSet<T> objectSet = (ObjectSet<T>)GetTheObjectSet(typeof(T));

    // This is a valid cast since ObjectSet<T> is derived from ObjectQuery
    ObjectQuery objectQuery = (ObjectQuery)GetTheObjectSet(typeof(T));
    return objectQuery.OfType<T>().SingleOrDefault((e) => e.Id == id);
}

解决的办法是强制转换对象集到的ObjectQuery并做查询那里。这里最重要的部分是的ObjectQuery为不是通用的,所以剧组经过精细。

The solution was to cast ObjectSet to ObjectQuery and do the query there. The most important part here is that ObjectQuery is not generic, so the cast goes through fine.

我必须给予一定的学分 Bennor麦卡锡,因为他是一个指向我OfType +铸造的ObjectQuery(一个事实,即对象集:的ObjectQuery)。谢谢!

I must give some credits to Bennor McCarthy as he was the one to point me to OfType + casting to ObjectQuery (the fact that ObjectSet : ObjectQuery). Thanks!

这篇关于实体框架:对象集和它的(仿制药)的方差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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