簡體   English   中英

實體框架和DbSet

[英]Entity Framework and DbSet

我正在嘗試設置一個通用接口來從存儲庫中檢索實體。 問題是我需要從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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM