【问题标题】:Entity Framework and DbSet实体框架和 DbSet
【发布时间】:2013-02-10 19:51:05
【问题描述】:

我正在尝试设置一个通用接口来从存储库中检索实体。 问题是我需要从 WCF 服务请求数据,而泛型不适用于操作合同,据我所知。

所以我有这个在控制台应用程序中工作,而不是使用服务调用:

public virtual List<T> GetAll<T>() where T : MyBaseType
{
   return this.datacontext.Set<T>().Include(l => l.RelationshipEntity).ToList();
}

我能看到 dong 的唯一方法是:

public virtual List<MyBaseType> GetAll(Type entityType)
{
   return this.datacontext.Set(entityType).Include(l => l.RelationshipEntity).ToList();
}

Set&lt;T&gt;()Set(Type type) 都返回 DbSet 但是,Set(Type type) 没有使用 ToList() 的扩展名,我也没有得到所有结果。

Local 属性仅显示当前执行范围内的上下文,而不是存储库中包含的内容。

所以我想要这样的 WCF 合同:

[ServiceContract]
public interface IRulesService
{
     [OperationContract]
     MyBaseType Add(MyBaseType entity);

     [OperationContract]
     List<MyBaseType> GetAll(Type type);
}

然后执行:

public virtual List<MyBaseType> GetAll(Type entityType)
{
    var dbset = this.datacontext.Set(entityType);
    string sql = String.Format("select * from {0}s", type.Name);

    Type listType = typeof(List<>).MakeGenericType(entityType);
    List<MyBaseType> list = new List<MyBaseType>();

    IEnumerator result = dbset.SqlQuery(sql).GetEnumerator();

    while (result.MoveNext()){
        list.Add(result.Current as MyBaseType);
    }

    return list;
}

//public virtual List<T> GetAll<T>() where T : MyBaseType
//{
//   return this.datacontext.Set<T>().Include(l => l.RelationshipEntity).ToList();
//}

public virtual MyBaseType Add(MyBaseType entity)
{
    DbSet set = this.datacontext.Set(typeof(entity));
    set.Add(entity);
    this.datacontext.SaveChanges();
    return entity; 
}

//public virtual T Add<T>(T t) where T : MyBaseType
//{
//   this.datacontext.Set<T>().Add(t);
//   this.datacontext.SaveChanges();
//   return t;
//}

public virtual List<MyBaseType> UpdateAll(List<MyBaseType> entities)
{

}

任何想法最好的方法?

【问题讨论】:

    标签: c# wcf entity-framework-4


    【解决方案1】:

    您应该可以调用Cast&lt;T&gt; 扩展方法。

    public virtual List<MyBaseType> GetAll(Type entityType)
    {
       return this.datacontext.Set(entityType)
           .Include(l => l.RelationshipEntity)
           .Cast<MyBaseType>()  // The magic here
           .ToList();
    }
    

    【讨论】:

    • 另外,当我尝试.Cast(MyBaseType&gt; 时,我得到了一个例外。 Cannot create a DbSet&lt;MyBaseType&gt; from a non-generic DbSet for objects of type 'MyDerivedType'.
    • @Gabe 你能分享一下你到底在做什么吗?
    • 我更新了我的问题,让我知道是否可以澄清或者您是否需要更多信息。我只是想在 wcf 上有一个通用提供程序。我可以使用 DbSet&lt;T&gt;() 做到这一点,但 WCF 不喜欢泛型。所以我试图与DbSet(Type type)
    最近更新 更多