通用存储库实现与EF [英] Generic repository implementation with EF
问题描述
对于简单的存储库
public interface ISimpleRepository< T>
{
IApplicationState AppState {get;组; }
void Add(T instance);
void Delete(T instance);
void Delete(Guid rowGuid);
IQueryable< T>得到所有();
T Load(Guid rowGuid);
void SaveChanges();
void Update(T instance);
}
我执行 Load()$
产品
的特定存储库的c $ c>方法可能如下所示:
public Product Load(Guid rowid)
{
return(from c in _ctx.Products where c.id == rowid select c).FirstOrDefault();
}
现在我的存储库实现类看起来像这样:
public class EntityFrameworkProductsProvider:IRepository< Product> ...
如果我喜欢几十个或几百个这样小而简单的实体,做CRUD时使用相同的行为(使用相同的方法实现)?我当然不想去创建一个类来为其中的每一个实现IRepository。
我想要这样的东西:
public class EntityFrameworkDefaultProvider< T> :IRepository< T> ...
但是我不知道如何实现LINQ Select表达式,因为当然我不能在_ctx.T中的e中写入,其中e ...
或者我吗?
因为到目前为止,我只有具有自定义存储库实现的非常具体的实体。
而不是写code> _ctx.Products ,您可以写入 _ctx.Set< T>
。这需要处理一半的问题(您需要在您的存储库中添加一个通用约束,其中T:class
)
然后,如果rowid是对象的键,则可以使用 _ctx.Set&T; .Find(rowid)
而不是按Id检索的LINQ查询。 p>
或者,您可以创建基本界面 IHaveId
(或 BaseEntity
class,无论你喜欢什么),它有 Id
属性,然后将其添加为T的一般约束,以便您可以在查询中使用它。 >
For a simple repository
public interface ISimpleRepository<T>
{
IApplicationState AppState { get; set; }
void Add(T instance);
void Delete(T instance);
void Delete(Guid rowGuid);
IQueryable<T> GetAll();
T Load(Guid rowGuid);
void SaveChanges();
void Update(T instance);
}
my implementation of the Load()
method for specific repository for class Product
might look like this:
public Product Load(Guid rowid)
{
return (from c in _ctx.Products where c.id == rowid select c).FirstOrDefault();
}
Now this is assumed when my repository implementation class looks like this:
public class EntityFrameworkProductsProvider : IRepository<Product> ...
What if I had like dozens or hundreds of this small and simple entities that would all use the same behaviour when doing CRUDs (use the same implementation of methods)? I certainly don't want to go and create a class to implement IRepository for each one of them..
I want something like this:
public class EntityFrameworkDefaultProvider<T> : IRepository<T> ...
but I don't know how to implement the LINQ Select expression then because of course I can't write from e in _ctx.T where e...
or do I?
I haven't run into this scenario yet because so far I only had very specific entities with custom repository implementation.
Instead of writing _ctx.Products
, you can write _ctx.Set<T>
. That takes care of half of the problem (you need to add a generic constraint where T: class
to your repository)
Then, if rowid is the object's key, you can use _ctx.Set<T>.Find(rowid)
instead of a LINQ query to retrieve by Id.
Alternatively, you can create a base interface IHaveId
(or a BaseEntity
class, whatever you like) which has the Id
property, and then add that as an generic constraint on T, so you can use it in your queries.
这篇关于通用存储库实现与EF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!