[英]Entity Framework and DbSet
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.
问题是我需要从WCF服务请求数据,而Generics不能使用操作合同,我可以看到。
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. Set<T>()
和Set(Type type)
都返回DbSet
但是Set(Type type)
没有使用ToList()
的扩展名,也没有返回所有结果。
The Local
property is only showing the context in scope of the current execution, not what is contained in the repository. Local
属性仅显示当前执行范围内的上下文,而不显示存储库中包含的内容。
So I want to have a WCF Contract like this: 所以我想要这样的WCF合同:
[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? 任何想法最好的方法?
You should be able to call the Cast<T>
extension method. 您应该能够调用
Cast<T>
扩展方法。
public virtual List<MyBaseType> GetAll(Type entityType)
{
return this.datacontext.Set(entityType)
.Include(l => l.RelationshipEntity)
.Cast<MyBaseType>() // The magic here
.ToList();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.