实体框架和DbSet [英] Entity Framework and DbSet

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

问题描述

我正在尝试建立一个通用接口以从存储库中检索实体。
问题是,我需要从WCF服务中请求数据,而从我所看到的情况来看,泛型无法使用操作合同。

I am trying to set up a generic interface to retrieve entities from a repository. The problem is that I need to request data from a WCF service and Generics don't work with operation contracts, from what I can see.

所以我使其可以在控制台应用程序中工作,而无需使用服务调用:

So I have this which works in a console application, not using a service call:

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

我看到洞的唯一方法是:

The only way I could see dong this would be something like:

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

Set< T>() Set(Type type)都返回 DbSet ,但 Set(Type类型)没有使用 ToList()的扩展名,也没有得到我所有的结果。

Set<T>() and Set(Type type) both return a DbSet but, Set(Type type) doesn't have the extension to use ToList(), nor do I get all my results back.

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

The Local property is only showing the context in scope of the current execution, not what is contained in the repository.

所以我想拥有这样的WCF合同:

So I want to have a WCF Contract like this:

[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)
{

}

有什么想法是最好的方法吗?

Any ideas the best approach?

推荐答案

您应该可以调用 Cast< T> 扩展名

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

这篇关于实体框架和DbSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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