Replacement for Fluent API

1

I'm in a project of a system that uses C # language, using MVC, Entity Framework and I'm using the Fluent API. I wonder if you have any other way to do this.

HasKey(oc => oc.OrdemCompraId);

HasRequired(oc => oc.UsuarioCadastro)
   .WithMany(oc => oc.OrdemCompraCadastrados)
   .HasForeignKey(oc => oc.UsuarioCadastroId);

HasOptional(oc => oc.UsuarioLiberacao)
   .WithMany(oc => oc.OrdemCompraCadastrados)
   .HasForeignKey(oc => oc.UsuarioLiberacaoId);

Property(oc => oc.Prioridade)
   .IsRequired();

HasRequired(oc => oc.Filial)
    .WithMany(oc => oc.OrdemCompras)
    .HasForeignKey(oc => oc.FilialId);
    
asked by anonymous 28.09.2015 / 18:50

1 answer

3

I'm assuming the entity is called OrdemCompra :

public class OrdemCompra
{
    ...
    public int UsuarioCadastroId { get; set;}

    ...
    public virtual Usuario UsuarioCadastro { get; set; }
}

And in Usuario :

public class Usuario
{
    ...
    public virtual ICollection<OrdemCompra> OrdemCompraCadastrados { get; set; }
}

However, since you are mapping several cardinalities 1 to N involving Usuario and OrdemCompra , you can not completely escape the Fluent API . You would need to have:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<OrdemCompra>()
                .HasRequired(oc => oc.UsuarioCadastro)
                .WithMany(u => u.OrdemCompraCadastrados)
                .HasForeignKey(oc => oc.UsuarioCadastroId)
                .WillCascadeOnDelete(false);
}

At the end, it looks like this:

public class OrdemCompra
{
    ...
    public int UsuarioCadastroId { get; set; }
    public int UsuarioLiberacaoId { get; set; }

    ...
    public virtual Usuario UsuarioCadastro { get; set; }
    public virtual Usuario UsuarioLiberacao { get; set; }
}

public class Usuario
{
    ...
    public virtual ICollection<OrdemCompra> OrdemCompraCadastrados { get; set; }
    public virtual ICollection<OrdemCompra> OrdemCompraLiberados { get; set; }
}

And the mapping:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<OrdemCompra>()
                .HasRequired(oc => oc.UsuarioCadastro)
                .WithMany(u => u.OrdemCompraCadastrados)
                .HasForeignKey(oc => oc.UsuarioCadastroId)
                .WillCascadeOnDelete(false);

    modelBuilder.Entity<OrdemCompra>()
                .HasRequired(oc => oc.UsuarioLiberacao)
                .WithMany(u => u.OrdemCompraLiberados)
                .HasForeignKey(oc => oc.UsuarioLiberacaoId)
                .WillCascadeOnDelete(false);
}
    
28.09.2015 / 19:23