【问题标题】:Entity framework with IN Clause in Repository Pattern存储库模式中具有 IN 子句的实体框架
【发布时间】:2014-07-10 17:55:56
【问题描述】:

我正在寻找有关如何在存储库模式中实现 IN 子句的帮助。我将拥有一组 ID,而不是对每条记录进行一次调用,将此 ID 传递给 Context 以使用带有 EF 的存储库模式获取满足条件的实体。

我知道我们可以有这样的东西:

context.Students.Where( x => StudentIDs.contains(x.ID))

如何在存储库层或模式中通过一次调用 DB 来实现相同的功能?

【问题讨论】:

  • 只公开 IQueryable。
  • 那么这个 context.Students.Where(x => StudentIDs.contains(x.ID)) 与 Repository 模式有什么冲突?

标签: entity-framework entity-framework-5 entity-framework-4.1


【解决方案1】:

如果你真的是一个纯粹主义者,是的,你应该完全按照你的暗示抽象 DbContext

我不确定我是否完全理解这个问题,但类似的事情应该可以解决问题:

namespace EFRepo
{
    class Student
    {
        public long Id { get; set; }
        public string Name { get; set; }
    }

    class SchoolContext : DbContext
    {
        public DbSet<Student> Students { get; set; }
    }

    class SchoolRepository
    {
        private SchoolContext context = new SchoolContext();

        public Student Add(string name)
        {
            Student student = new Student { Name = name };

            context.Students.Add(student);

            context.SaveChanges();

            return student;
        }

        public IEnumerable<Student> GetStudentsByIds(IEnumerable<long> ids)
        {
            return context.Students.Where(x => ids.Contains(x.Id));
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            SchoolRepository repo = new SchoolRepository();

            repo.Add("Bully");
            repo.Add("Crawler");
            repo.Add("Tart");

            foreach (Student s in repo.GetStudentsByIds(new[] { 1L, 3 }))
            {
                Console.WriteLine(s.Name);
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2012-09-02
    • 2011-11-02
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    相关资源
    最近更新 更多