加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 实体框架和DbSet

发布时间:2020-12-15 07:50:54 所属栏目:百科 来源:网络整理
导读:我正在尝试设置一个通用接口来从存储库中检索实体. 问题是我需要从WCF服务请求数据,而Generics不能使用操作合同,我可以看到. 所以我有一个在控制台应用程序中工作,而不是使用服务调用: public virtual ListT GetAllT() where T : MyBaseType{ return this.d
我正在尝试设置一个通用接口来从存储库中检索实体.
问题是我需要从WCF服务请求数据,而Generics不能使用操作合同,我可以看到.

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

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

我能看到这个的唯一方法是:

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

}

任何想法最好的方法?

解决方法

你应该可以调用Cast< T>扩展方法.
public virtual List<MyBaseType> GetAll(Type entityType)
{
   return this.datacontext.Set(entityType)
       .Include(l => l.RelationshipEntity)
       .Cast<MyBaseType>()  // The magic here
       .ToList();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读