存储库是否应返回IEnumerable< T>. ,IQueryable< T>或List< T&gt ;? [英] Should a Repository return IEnumerable<T> , IQueryable<T> or List<T>?

查看:90
本文介绍了存储库是否应返回IEnumerable< T>. ,IQueryable< T>或List< T&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使我的应用程序尽可能地灵活,但不要通过使我的界面过于具体而陷入困境.

I'd like to make my application as flexible as possible, but not dig myself into a hole by making my Interface too specific.

存储库的最佳对象类型是什么? IEnumerable,IQueryable还是List?

What is the best object type for a repository? IEnumerable, IQueryable, or List?

我正在考虑使用的技术是

The technologies I'm considering using are

  • Azure App Fabric缓存

  • Azure App Fabric Caching

实体框架4.1

可能是Windows Server AppFabric

Possibly Windows Server AppFabric

推荐答案

我想说的是,使用IQueryable构建DAL,并将其传递给他人,以确保您的对象包含生存期.这样,您将获得延迟执行的好处,但是却面临数据库查询效率低下的风险.

I would say build your DAL using IQueryable, and pass it around, make sure your object contects lifetime is the request. This way you will get benefit of delayed execution, but are exposed to the risk of inefficient querying of database.

然后确保对您的应用程序进行性能测试(或至少是最有可能获得流量的部分)并查看数据访问模式.在DAL中创建专门的方法,以检索完全实现的对象并将这些查询作为预编译查询.

Then make sure you performance test your application( or atleast the parts that are most likely to get traffic) and see the dataaccess patterns. Create specialized methods in your DAL to retreive fully materialized onjects and make these queries as pre compiled queries.

存储库接口的示例类似于

a sample of the repository interface would be like

  public interface IDataContext
  {
        void Add<T>(T entity) where T : BaseEntity;
        void Delete<T>(T entity) where T : BaseEntity;
        IQueryable<T> Find<T>(Expression<Func<T, bool>> where) where T : BaseEntity;
   }

其中BaseEntity是我们所有类的基类,该类未映射到db中的任何表

where BaseEntity is the base class to all our classes, it looks like, this class is not mapped to any table in db

public abstract class BaseEntity
{
        public int Id { get; set; }
        public DateTime CreateDateTime { get; set; }
        public string CreateUser { get; set; }
        public DateTime ModDateTime { get; set; }
        public string ModUser { get; set; }
        public byte[] RowVersion { get; set; }
}

Expression<Func<T, bool>>会将整个表达式传递给您的存储库,而不仅仅是Func,因为EF会根据表达式来生成sql查询,所以典型的用法是

Expression<Func<T, bool>> would pass the whole expression to your repository instead of just Func, since EF works on expression to generate sql query, a typical use would be

ICollection<WFGroup> wgGroups = this.dataContext.Find<WFGroup>((w) => true).ToList();

其中WFGroup是从BaseEntity派生的类,我通常使用延迟加载和代理,并且不要将对象分离/附加到上下文.

where WFGroup is a class derived from BaseEntity, I typically use lazy loading and proxy and dont detach/attach objects to a context.

这篇关于存储库是否应返回IEnumerable&lt; T&gt;. ,IQueryable&lt; T&gt;或List&lt; T&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆