Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ApplicationDbContext - where it belongs in project [closed]

I want to use one (EF) context file in my mvc 5 app and I want to use asp identity.

I have a few projects in solution DAL, GUI and WebAPI.

I want to just move ApplicationDbContext in DAL assembly and remove EF completly from my UI project.

What you do with ApplicationDbContext and asp identity when you start your new projects?

Do you leave it in UI layer or you moving it to data layer?

I really don't have any experienced dev to ask I hope it will not be downvoted.

like image 578
1110 Avatar asked Sep 13 '14 22:09

1110


People also ask

What is ApplicationDbContext?

The ApplicationDbContext links the database server to the data model classes in the Asp.Net application. This only calls dbContext. Table1. Field1 and has the value of a data table.

What is the use of entity context object?

The context class manages the entity objects during run time, which includes populating objects with data from a database, change tracking, and persisting data to the database.

What is context class in Entity Framework?

The context class in Entity Framework is a class which derives from System. Data. Entity. DbContextDbContext in EF 6 and EF Core both. An instance of the context class represents Unit Of Work and Repository patterns wherein it can combine multiple changes under a single database transaction.


3 Answers

I presume you're talking about Entity Framework's DbContext? If so then you're right to keep this in your DAL assembly.

Moving it and changing your namespace is all you need to do.

like image 162
Joseph Woodward Avatar answered Oct 04 '22 18:10

Joseph Woodward


Separating Identity:

Separating Identity from the UI is much trickier. Here, Microsoft has entangled them so closely that I would recommend leaving it until you understand Identity, EF, and the Repository Pattern at an expert level.

But, in case you are interested in separating Identity from the UI Level, here is a great resource from Dino Esposito


  • Notice the reference to ApplicationDbContext in your Account Controller's Constructor:

    public AccountController()
        : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>
                             (new ApplicationDbContext())))
    

This can easily be a reference to a Context in your DAL.

  • you will have great difficulty using a Repo over a context. That would require re-writing the UserManager which I highly doubt you want to do.

  • You can create a child that inherits from ApplicationDbContext and is abstracted with an Interface

:

public class UserIdentityContext : ApplicationDbContext, IUserIdentityContext 

Now you can use Ninject to bind your Account Controller to an Abstract Pattern

public AccountController()
    : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>
                         (IUserIdentityContext identityContext)))

But none of these moves allow you to remove EF assemblies from your UI Project. Here Microsoft bound the Data and UI elements too closely. You would have to re-write the Account Controller.

It's an issue they are dealing with and will probably improve on greatly in a MVC 6 / Identity 3

like image 44
Dave Alperovich Avatar answered Oct 04 '22 17:10

Dave Alperovich


It is possible and not that difficult to remove the ApplicationDbContext from your ui project. The most complete way is to create a webapi project that will expose the functions of the IUserStore, or at least just the functions you need, and you won't need them all. The web api methods just delegate to the underlying entityframework, used in a DAL or not. Like (with a repository)

  [HttpGet]
  [Route("finduserbyid/{userId}")]
  public async Task<IHttpActionResult> FindByIdAsync(string userId)
  {
     var verifiedUser = await this.UnitOfWork.ApplicationUserRepository.FindByIdAsync(userId);

     if (verifiedUser == null)
     {
        return NotFound();
     }

     return Ok(verifiedUser);
  }

Then create a new class in your ui project, or a utility project that implments IUserStore and calles the webapi for the data. I was able to do this in a day or so, not very difficult. Like this:

public class RemoteUserStore<T> : IUserStore<ApplicationUser>
    , IUserPasswordStore<ApplicationUser>
    , IUserLoginStore<ApplicationUser>
    , IUserRoleStore<ApplicationUser>
    , IUserEmailStore<ApplicationUser>
{
    public RemoteUserStore(string identityServerUrl)
    {
        _appServerUrl = identityServerUrl;
    }

    private readonly string _appServerUrl;
    private string IdentityServerUrl
    {
        get
        {
            return _appServerUrl;
        }
    }


    public async Task CreateAsync(ApplicationUser user)
    {
        var client = new HttpClient();
        string url = string.Format("{0}/api/identity/createuser/{1}", IdentityServerUrl, user.Id);

        var userContent = MapApplicationUserToFormContent(user);
        var result = await client.PostAsync(url, userContent);
    }

   //snip
}

You will not be able to eliminate a reference to entity framework however, as the UI will actually use the ApplicationUser with IdentityUser as a base class and it is defined in the microsoft.aspnet.identity.entityframework package

like image 40
Philip Nelson Avatar answered Oct 04 '22 17:10

Philip Nelson