i am working on a big Project, where an IIS-Application, a WCF-Service and a normal application have access to the same database with the same model-classes. Now I`d like to ask if and how it is possible to put the DBContext in a class-library so that every other Project can use that context.
Here is a small part of my DB_Entities in the class library:
using ManagementLibrary.Model;
using System.Data.Entity;
namespace ManagementLibrary.EntityFramework
{
public class DB_Entities : DbContext
{
public DB_Entities() : base(nameOrConnectionString: "DatabaseConnection") { }
public DbSet<User> Users{ get; set; }
// more sets here
}
}
I tried to insert the Connection-string and configuration in the App.config of my Client-Application:
Registering the Provider:
<system.data>
<DbProviderFactories>
<remove invariant="Npgsql" />
<add name="Npgsql Data Provider" invariant="Npgsql" support="FF" description=".Net Framework Data Provider for Postgresql" type="Npgsql.NpgsqlFactory, Npgsql" />
</DbProviderFactories>
</system.data>
Adding the Connection String:
<connectionStrings>
<add name="DatabaseConnection" connectionString="server=192.168.0.2;Port=5432;user id=postgres;password=postgres;database=ManagementDatabase" providerName="Npgsql" />
</connectionStrings>
The rest of the EF-Config:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v13.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="Npgsql" type="Npgsql.NpgsqlServices, EntityFramework6.Npgsql" />
</providers>
</entityFramework>
Now, when I want to add the migrations, it does not work.
PM> Enable-Migrations
No context type was found in the assembly 'ConsoleTestClient'.
There is even something more complicadet: In my Class Library there is a controller-class which has the DB_Entities as an Attribute. I want to use that controller-class in each Project, so that i have to write the rules for the database-operations just once. The controller-class is very big and contains many methods, here is just a very small part so that you can see what i want to do:
public class UserController: Controller
{
public User insertUser(User newUser)
{
entities.Users.Add(newUser);
}
//a lot of more methods here
}
The Controller is an Abstract class which contains a private attribute entities (Type: DB_Entities).
So, a lot of text for this small question: How do I have to configure my Projects to be able to use all my Controllers and DB_Entities that are in a class library?