I usually use the entity framework in an MVC project but I would like to know if I can use it from a class library project
I usually use the entity framework in an MVC project but I would like to know if I can use it from a class library project
Yes, it is entirely possible to separate the project into class libraries
until you have a question here in SO-PT about performance
Example of how to split into projects:
In a blank solution create 3 projects, which are
i) ProjectName.Classes (here will be the project classes);
ii) DesignName.Entity (here will be entity settings)
iii) ProjectName.MVC (this will be the web layer)
In the classes layer, create a class, for example:
public class Pessoa
{
public int PessoaId { get; set; }
public string Nome { get; set; }
public string Sexo { get; set; }
}
On the Entity layer, install the entity Install-Package EntityFramework
from the package manager console or the nuget
. Create a context class, for example:
public class EntitySeparadoDbContext : DbContext
{
public EntitySeparadoDbContext()
{ }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//No exemplo está sendo usuário o EntityTypeCOnfiguration para configurar como ficará a classe no banco
modelBuilder.Configurations.Add(new PessoaConfiguration());
}
public DbSet<Pessoa> Pessoas { get; set; }
}
Then you can enable migrations ( enable migrations
), add them ( add-migration <nome>
) and execute them ( update-database
)
NOTE: You need to set the Entity project by default in the package manager console
Afterthat,intheMVClayeryoujustneedtoinstantiatethecontextanduseitnormally,eg:
privateEntitySeparadoDbContextdb=newEntitySeparadoDbContext();publicActionResultDetails(int?id){if(id==null){returnnewHttpStatusCodeResult(HttpStatusCode.BadRequest);}Pessoapessoa=db.Pessoas.Find(id);if(pessoa==null){returnHttpNotFound();}returnView(pessoa);}
Imadeanexampleprojectanduploadediton GitHub
Maybe you also want to see about: