Can I abstract Entity Framework away from my Entities?

前端 未结 5 1373
南方客
南方客 2021-02-08 15:43

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:18

    The general concept you are referring to is "persistence ignorance" (PI), although that generally applies directly to entities themselves rather than the code that consumes the entities.

    In any case, Hibernate and NHibernate natively support PI, but the initial version of Microsoft's Entity Framework does not. MS caught a lot of flak for this and PI is probably the #1 most discussed feature for the next version (whenever that is).

    As far as what you are trying to do with interfaces, does the collection of Bars need to be modified after it is retrieved? If the answer is yes, there is no easy answer. Even covariance couldn't help you here because ICollection has an Add method.

    If the collection is read-only, then you might consider exposing it as IEnumerable. The Enumerable.Cast method makes this fairly convenient.

    interface IFoo
    {
        IEnumerable Bars { get; }
    }
    
    partial class Foo : IFoo
    {
        IEnumerable IFoo.Bars
        {
            get { return Bars.Cast(); }
        }
    }
    

    Also, I know of at least one effort to make the current version of EF support persistence ignorance.

提交回复
热议问题