![](/img/trans.png)
[英]EntityFramework 6.1.3: The type 'IdentityDbContext<>' is defined in an assembly that is not referenced
[英]WCF Service with EntityFramework, giving error “The type 'DBContext' is defined in an assembly that is not referenced”
我正在使用WCF服務應用程序使用EF進行數據訪問。 我在DataLayer下的所有EF模型。 我在數據層下創建了以下工廠方法
namespace TRA.Services.DataAccessLayer
{
public static class DataObjectFactory
{
public static TRAEntities CreateTRAContext()
{
return new TRAEntities();
}
}
}
在業務層中,我嘗試使用以下代碼:
using (var context = DataObjectFactory.CreateTRAContext())
{
var objClients = from r in context.TRAEmployee
orderby r.id
select r;
}
它給我以下錯誤: “類型'DBContext'是在未引用的程序集中定義的。您必須添加對程序集'EntityFramework,Version = 6.0.0.0,......的引用”。
由於我在業務層中使用此代碼,因此我不想添加對EntityFramework的引用。
有什么辦法可以處理這種情況?
如果要從程序public static TRAEntities
的類成員公開的類型( public static TRAEntities
,其中TRAEntities : DbContext
)中公開的每個類型都必須引用程序集,則它們必須使用該成員。
因此,因為您要從業務層公開和訪問DataObjectFactory.CreateTRAContext()
,並且從該方法返回的類型繼承自Entity Framework的DbContext
,所以您的業務層需要對Entity Framework的引用。
您可以通過引入一個間接層來解決此問題,在這種情況下,通常通過某個存儲庫層來完成。 這也使您的業務層可測試,而不必模擬實體框架。
因此,而不是在拉DbContext
從數據層和訪問其DbSet<T>
的成員,你暴露庫這反過來又會使您要訪問的實體:
public interface IRepository<T>
{
IQueryable<T> Entries();
}
此存儲庫的實現在數據層內部,並且包裝DbSet<T> DbContext.Set<T>
。
這里的問題更多是概念上的。 與其公開返回TRAEntities
實例的方法, TRAEntities
創建一個Accessor
來將雇員列表返回到bsuness邏輯層,例如:
IEnumerable<Employee> GetEmployees()
{
IEnumerable<Employee> employees;
using (var context = DataObjectFactory.CreateTRAContext())
{
employees = from r in context.TRAEmployee
orderby r.id
select r;
}
return employees;
}
此外,如果層之間的抽象很重要,請實現一個單獨的Employee實體,以將數據移出數據訪問層。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.