Can I abstract Entity Framework away from my Entities?

前端 未结 5 1279
野性不改
野性不改 2021-02-08 16:03

I have a Foo entity in Entity Framework. But I\'m making it inherit from IFoo so that my business logic only knows IFoo - thus abstracting

5条回答
  •  醉话见心
    2021-02-08 16:28

    We've been doing the exact same thing for LINQ to SQL. I got around the collection issue by writing a class which wraps an IList and casts to and from the correct type as required. It looks a bit like this:

    public class ListWrapper : IList
        where TTarget : class
        where TSource : class, TTarget
    {
        private IList internalList;
    
        public ListWrapper(IList internalList)
        {
            this.internalList = internalList;
        }
    
        public void Add(TTarget item)
        {
            internalList.Add((TSource)item);
        }
    
        public IEnumerator GetEnumerator()
        {
            return new EnumeratorWrapper(internalList.GetEnumerator());
        }
    
        // and all the other IList members
    }
    

    EnumeratorWrapper similarly wraps an IEnumerator and performs the casting. In the LINQ to SQL partial classes we expose the property like this:

    public IList Foos
    {
        get
        {
            return new ListWrapper(this.Foos_internal);
        }
    }
    

    Any changes to the exposed list will be performed on the internal EntitySet so they stay in sync.

    This works well enough but my feeling is that this whole approach is more trouble than it's worth, I'm a huge NHibernate fan and a strong believer in P.I. but we've put in a LOT of extra effort doing this and haven't really seen any advantage. We use the repository pattern to abstract away the actual DataContext access which I would say is the key part of decoupling ourselves from LINQ to SQL.

提交回复
热议问题