0

I have 2 folders:

My-WebApplication
My-WebService

Both are 2 asp.net mvc 6.0 project in an extra visual studio solution.

Both need to share a custom DbContext class using Entity Framework 7.

I use Visual Studio 2015 and develop against

"frameworks" : { "net451" }

Where would you create the custom DbContext class and how would you share it among both VS solutions using the latest features of Visual Studio 2015 concerning class libraries as nuget packages - if that helps -

OR

should I just create a class library and put that in a 3rd share.sln file in a 3rd folder on the same level as the others? and both solutions reference then this class library?

Elisabeth
  • 20,496
  • 52
  • 200
  • 321

1 Answers1

0

You can use a common DbContext in a separate assembly (package class library) . DbContext is initiated separately for each project in ConfigureServices of Startup.cs

services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext<YourDbContext>(options => options.UseSqlServer(Configuration["Data:ConnectionString"]));

It is necessary to specify dependencies for each project in project.json

"dependencies": {
    ...
    "YourProject.Data": "1.0.0.0",
    ...
}

where YouProject.Data is an assembly with YourDbContext.

Also you need to add dependencies and the command in YouProject.Data project.json for a configuration of migrations for your context:

"dependencies": {
    "EntityFramework.SqlServer": "7.0.0-beta7",
    "EntityFramework.Commands": "7.0.0-beta7"
}
"commands": {
    "ef": "EntityFramework.Commands"
},

You can use the next command for a creation of new migration (for MVC6 beta-7)

dnx ef migrations add NameOfMigraion -c YourDbContext -s YouApplicationProjectName

where YouApplicationProjectName is a name of your asp.net mvc6 project name, for example My-WebApplication or My-WebService

I hope this will help you.

hcp
  • 3,268
  • 6
  • 26
  • 41
  • When each project`s project.json references the "YourProject.Data".assembly, where is this assembly put? In which file location? folder 1 or folder 2 and why you decide for that? – Elisabeth Sep 18 '15 at 13:28
  • If you have a separate solutions, you can put the assembly anywhere but you must add it in both solutions to keep references. – hcp Sep 18 '15 at 13:52
  • ok I build those assembly to share in a CommonShare folder on the same directory level as both solutions. That way each solution can reference the assembly. Is there an advantage in using a class library as nuget package here? Else I use a common class library. – Elisabeth Sep 18 '15 at 16:14
  • There are a [number of benefits](http://stackoverflow.com/questions/28034174/why-create-an-asp-net-5-class-library-project) of _Class Library (Package)_ over _Class Library (.csproj)_ projects: – hcp Sep 19 '15 at 06:10