Replacement for the Fluent API

Asked

Viewed 87 times

1

I am in a project of a system that uses the C#language, using MVC, Entity Framework and I am using the Fluent API. I wonder if there’s another way to do it.

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);

1 answer

3


I’m guessing 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; }
}

Only, as you are mapping several cardinalities 1 to N involving Usuario and OrdemCompra, there is no way to completely escape from Fluent API. 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);
}

In the end, it stays 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);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.