I'm studying the EntityFramework, writing two contexts to understand how to deal with it when my domain contains many entity classes . That would then be represented by many DbSet's in context, making their startup "heavy." I imagine this is the right way to work when you have a model with many classes!
So I started my tests by typing the following domain, for testing purposes only:
public class Empresa
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[StringLength(70)]
public string RazaoSocial { get; set; }
}
public class Usuario
{
[Key]
[StringLength(150)]
public string Login { get; set; }
[StringLength(50)]
[DataType(DataType.Password)]
public string Senha { get; set; }
}
The context I created as follows:
public class EfConfiguration : DbConfiguration
{
public EfConfiguration() {
SetProviderServices(SqlProviderServices.ProviderInvariantName,
SqlProviderServices.Instance);
SetDefaultConnectionFactory(new SqlConnectionFactory());
}
}
[DbConfigurationType(typeof(EfConfiguration))]
public abstract class CustomContext : DbContext
{
protected CustomContext(): base("DefaultConnection") {
Configuration.LazyLoadingEnabled = false;
Configuration.ProxyCreationEnabled = false;
}
}
public class EmpresaContext : CustomContext
{
public DbSet<Empresa> Empresas { get; set; }
}
public class UsuarioContext : CustomContext
{
public DbSet<Usuario> Usuarios { get; set; }
}
So there's the App.config of my console application to test:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="DefaultConnection"
connectionString="Data Source=(local);Initial Catalog=TestEF;Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
Anyway, not to put a lot more code on my app console to test:
static class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Instanciando as classes ...");
var empresaRepository = new EmpresaRepository<Empresa>();
var usuarioRepository = new UsuarioRepository<Usuario>();
Console.WriteLine("Obtendo ...");
empresaRepository.Obter();
usuarioRepository.Obter();
Console.WriteLine("Pronto!");
}
catch (Exception e)
{
Console.WriteLine(e.GetBaseException().Message);
}
Console.ReadKey();
}
}
The Obter()
methods will perform the following commands from my generic Repository class:
public IQueryable<T> Obter(Expression<Func<T, bool>> condition = null)
{
var result = (IQueryable<T>)_context.Set<T>();
if (condition != null)
result = result.Where(condition);
return result;
}
My problem is that the string "Ready!" of the last Console.WriteLine()
command is printed to the Windows console but the database is not being created. Anyway, no error message is being printed!
What might be causing this?
Obs : Without using DbConfiguration
and writing App's with EF the traditional way I have no problems.
EDIT
Following user guidelines Cigano Morrisson I tried to specify the creation of the bank using initializers for the context:
Database.SetInitializer (new DropCreateDatabaseAlways ()); Database.SetInitializer (new DropCreateDatabaseAlways ());
Unfortunately it did not work either!
So I tried Migrations too. For more than one context I had to specify:
Enable-Migrations -ContextTypeName EmpresaContext -MigrationsDirectory Migrations\EmpresaContext
Enable-Migrations -ContextTypeName UsuarioContext -MigrationsDirectory Migrations\UsuarioContext
Adding version:
Add-Migration -ConfigurationTypeName AppConsoleTest.Migrations.EmpresaContext.Configuration "Initial"
Add-Migration -ConfigurationTypeName AppConsoleTest.Migrations.UsuarioContext.Configuration "Initial"
Creating and updating database:
Update-Database -ConfigurationTypeName AppConsoleTest.Migrations.EmpresaContext.Configuration
Update-Database -ConfigurationTypeName AppConsoleTest.Migrations.UsuarioContext.Configuration
So the database was created. Both hit the same database and both tables appeared.
I then experimented by commenting on//[DbConfigurationType(typeof(EfConfiguration))]
of CustomContext
, I removed the Migrations files and also removed the Database.SetInitializer
initializers and when running the application, on the Obter()
methods of the repository objects ( empresaRepository
and usuarioRepository
) the base is created and the tables are also in the same bank. With this I deduced that the error is in my configuration class, the
EfConfiguration
.
What's wrong?