Entity Framework and DbSet

馋奶兔 提交于 2019-12-23 08:04:40

问题


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>() 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.

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

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);
}

Then the implementation:

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?


回答1:


You should be able to call the Cast<T> extension method.

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


来源:https://stackoverflow.com/questions/15070874/entity-framework-and-dbset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!