Search code examples
entity-frameworkentity-framework-6data-access-layerbll

How to / Should one - set EntityState in UI/BL Layer?


I have a segregation of layers as follows:

UI - Web App => References BLL And Entities

BLL - Business Logic (Validations) => References DAL And Entities

Entities - Data Carries (POCO) => No Reference

DAL - Data Context EDMX => No Reference

I have a very basic question, since this is my first project with absolute segregation. If I want to set EntityState (Added/Modified/Deleted) of my objects @ UI level, how do I do that. Because with the above structure I won't have access to the DataContext.

Because for all I know to set the Entity State, data context is a mandate.

I have read a lot questions on SO, but none had a clarification of this doubt. I know one other way would be maintaining a custom State property @ Entities level.

I have read that datacontext should be limited to DAL. Is it a bad practice to set EntityState it @BLL/UI?

I'm new to EF with this kind of architecture.Please help.

I have gone through the following So questions but did not get clarity, may be it is due to my lack of knowledge of SOC:

1.Which layer should create DataContext?

2.Why DbContext object shouldn't be referred in Service Layer?

3.If Entity Framework / DbContext is the DAL / Repository, where does it fit within 3-tier architecture?

4.Entity Framework and layer separation

4.How to update entities which are modified outside the DbContext?

EDIT 1: One thing I'm still concerned about is looping through the object hierarchy again in DAL just to set their EntityState.I have a pretty much nested hierarchy. If I had to do the same in a flat structure I would have to set it once in the UI where objects are filled and can then call context.savechanges().

But here I have made a dummy state property for entity, which I can set @UI and later translate that to EntityState.Modified @DAL. Is this a right approach?


Solution

  • Only your DAL should have access to your DataContext (indirectly). The DataContext should be created/retrieved by a ContextFactory that is inserted into your BaseRepository. Somewhere in your factory class you should have a method that retrieves the DataContext:

    public DataContext Get()
    {
        return _dataContext ?? (dataContext = new DataContext());
    }
    

    Let's say in your repository you have an Update(T entity) method, then that's where you handle the state:

    public void Update(T entity)
    {
        _dataContext.Entry(entity).State = EntityState.Modified;
    }