简体   繁体   中英

How to decouple EF objects from UI

I have an N-Tier app, UI, BLL and DAL. My DAL uses EF6 for all database interactions.

This means, if I query the database and then want to iterate over the object in my UI (such as a foreach loop to display values on screen) my UI has to know about the DAL. This seems incorrect. I'd like my DAL to know about nothing. The Bll can know of the DAL. And the UI can only know the BLL.

Please consider this simplified EF object

partial class Foo 
{
    public int Id { get; set; }
    public virtual ICollection<Bar> FooFoo { get; set; }
}

The only way I can think of is if I also have a Bll.Foo which maps the 2 objects. Then I thought, may be it's better if they both implement an Interface of IFoo. But Foo has a Collection of Bar, which also will need to be of type IBar. And this is where it goes wrong. Please consider:

class Foo : IFoo                                          //generated by EF
{
    public int Id { get; set; }                           //generated by EF
    public virtual ICollection<Bar> FooFoo { get; set; }  //generated by EF and KABOOM
}

interface IFoo
{
    ICollection<IBar> FooFoo { get; set; }   
}

class Bar : IBar
{
    public int MyPr
    { get; set; }
}

interface IBar
{
    int MyPr { get; set; }
}

The issue with the above, where I've shown the Kaboom, is the interface is not 'satisfied' as it comes via EF as type Bar , but the interface says I need to implement it as type IBar . Without this, I'm not decoupling...

How can I achieve this or is my understanding flawed?

Your idea about creating models and mapping the 2 is a sound way to separate UI from knowing anything about entities from DAL. Your BLL will have a BLL.Foo which maps the 2 objects. Your BLL exposes BLL.Foo so that they can be used by tiers above it. That way only BLL know about DAL entities.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM