代码之家  ›  专栏  ›  技术社区  ›  Darren Lewis

带有实体框架4.0的函数导入和存储库模式

  •  1
  • Darren Lewis  · 技术社区  · 14 年前

    Could anyone advise me on how they've implemented the use of Function Imports when using the Repository pattern against EF 4.0?

    我们有一个映射到候选实体的表,还有一个从映射到候选实体的现有存储过程导入的函数。这在ef中很有效,但是我们通过使用存储库来抽象,这些存储库接受其构造函数iobjectset,其中t是poco实体。但是,这意味着我无法获取对函数导入的引用。我能看到的唯一方法是将对ObjectContext的引用传递给需要它的存储库,但这对我来说有点像设计的味道。

    Even though several of our Repositories are extended with custom interfaces we're still faced with the same issue.

        public class CandidateRepository : Repository<Candidate>, ICandidateRepository
    {
        public CandidateRepository(IObjectSet<Candidate> entities)
            : base(entities)
        {
        }
    
        public Candidate GetByEmail(string email)
        {
            return Entities.SingleOrDefault(c => c.EmailAddress.Equals(email));
        }
    
        public bool CandidateExists(string candidateNumber)
        {
            return Entities.SingleOrDefault(c => c.Number.Equals(candidateNumber)) != null;
        }
    
        public Candidate GetByNumber(string number)
        {
            return Entities.SingleOrDefault(c => c.Number.Equals(number));
        }
    
        public Candidate GetMember(string number)
        {
    
            return new Candidate();  //This one needs to return from the Function Import
        }
    }
    

    任何建议都非常感谢。

    2 回复  |  直到 14 年前
        1
  •  1
  •   Yury Tarabanko    14 年前

    为了直接解决你的问题,你可以 entities ObjectSet<T> 使用 entites.Context 属性获取 ObjectContext .

    public Candidate GetMember(string number)
    {
        var objectSet = Enities as ObjectSet<Candidate>;
    
        if(objectSet == null) throw new Exception("Oh, it's not EF IObjectSet implementation");        
    
        return objectSet.Context.MyCustomFunction(string number);
    }
    

    如您所见,此代码依赖于特定的 IObjectSet 执行一点都不好。

    更好的方法是只为聚合根创建存储库,而不是为每个表创建存储库。所以通过比较自然 客体语境 到存储库ctor。

        2
  •  0
  •   zeeshanhirani    14 年前

    I have went down this route and i have experienced that it is less of a pain when you pass in an interface implementation of the ObjectContext to your repository. The interface implementation should have some way of calling the function. So when you pass in the concrete implementation of the ObjectContext everything should work fine.