I have this Many to Many template and I need to popular the table through the Seed file as described at the end of the post using api fluent / p>
Contextfile:
publicEfDbContext():base("EfDbContext") { }
public DbSet<TBUsuario> Usuarios { get; set; }
public DbSet<TBMenu> Menus { get; set; }
public DbSet<TBPerfil> Perfis { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<TBUsuario>().ToTable("TBUsuario");
modelBuilder.Entity<TBPerfil>().ToTable("TBPerfil");
modelBuilder.Entity<TBMenu>()
.HasMany<TBPerfil>(p => p.Perfis)
.WithMany(m => m.Menus)
.Map(pm =>
{
pm.MapLeftKey("TBMenuID");
pm.MapRightKey("TBPerfilID");
pm.ToTable("TBMenuPerfil");
});
}
Seed:
protected override void Seed(Lamar.Dominio.Repositorio.EfDbContext context)
{
var perfil = new List<TBPerfil>
{
new TBPerfil {PerfilID=1, Nome="Administrador" },
new TBPerfil {PerfilID=2, Nome="Operacional" }
};
perfil.ForEach(s => context.Perfis.AddOrUpdate(p => p.PerfilID, s));
context.SaveChanges();
var menus = new List<TBMenu>
{
new TBMenu{TBMenuID=1, Action="#", Controller=string.Empty, Icon="fui-user", Nome="Cadastros", Posicao=0, Tooltip="Cadastros" },
new TBMenu{TBMenuID=2, Action="Index", Controller="Clientes", Icon=string.Empty, Nome="Clientes", Posicao=1, Tooltip="Clientes" }
};
menus.ForEach(s => context.Menus.AddOrUpdate(p => p.TBMenuID, s));
context.SaveChanges();
}