Relationship 1 - N Entity Framework

Asked

Viewed 1,228 times

1

I’m developing a test project and I’m having a problem with 1-N relationship with the Entity.

Model Cab_venda:

  public Cab_Venda() {
   Det_Venda = new HashSet < Det_Venda > ();
  }

  public int id {
   get;
   set;
  }

  public int idCliente {
   get;
   set;
  }

  [Column(TypeName = "date")]
  public DateTime data {
   get;
   set;
  }

  [Required]
  [StringLength(6)]
  public string hora {
   get;
   set;
  }

  [Required]
  [StringLength(1)]
  public string situacao {
   get;
   set;
  }

  [Column(TypeName = "date")]
  public DateTime dataExpedicao {
   get;
   set;
  }

  [Column(TypeName = "date")]
  public DateTime dataAceite {
   get;
   set;
  }

  public virtual Usuario Usuario {
   get;
   set;
  }

  public virtual ICollection < Det_Venda > Det_Venda {
   get;
   set;
  }

Model Det_venda

    public int id {
  get;
  set;
 }

 public int idCab {
  get;
  set;
 }

 public int idProduto {
  get;
  set;
 }

 public int idPreco {
  get;
  set;
 }

 public virtual Cab_Venda Cab_Venda {
  get;
  set;
 }

 public virtual Preco Preco {
  get;
  set;
 }

 public virtual Produtos Produtos {
  get;
  set;
 }

I’m getting a collection of Products and need to insert a Cab_Venda and with the products of this sale on Det_Venda. In my Controller I have the following code:

    List < Det_Venda > listDetVenda = new List < Det_Venda > ();

using(var db = new LojaAppContext()) {

 var idUsuario = Int32.Parse(Session["idUsuario"].ToString());


 var carrinho = db.Carrinho.Where(p => p.idUsuario == idUsuario).ToList();

 Cab_Venda order = new Cab_Venda() {
  data = DateTime.Now,
   hora = "142626",
   situacao = "Aguardando liberação",
   dataExpedicao = DateTime.Now,
   dataAceite = DateTime.Now
 };

 db.Cab_Venda.Add(order);
 db.SaveChanges();


 List < Det_Venda > listProdutos = new List < Det_Venda > ();

 foreach(var item in carrinho) {

  Preco preco = db.Preco.FirstOrDefault(p => p.idProduto == item.idProduto);

  Det_Venda dt = new Det_Venda() {
   idCab = order.id,
    idProduto = item.idProduto,
    idPreco = preco.id
  };

  listProdutos.Add(dt);
 }

 listProdutos.ForEach(dt => db.Det_Venda.Add(dt));
 db.SaveChanges();
}

But when saving from the following error:

Validation failed for one or more entities. See 'Entityvalidationerrors' Property for more Details.

Linha 41:                 db.Cab_Venda.Add(order);
Linha 42:                 db.SaveChanges();

Would anyone know what to say?

  • Search for the error inside the Entityvalidationerrors property and share it with us. Apparently you are saving before Cab_venda without making the link with Dat_venda in a mandatory relationship!

1 answer

0

EF mapping, you can work in a dynamic way, you want 1-N type 1 Customer has N orders?

If yes;

public class Cliente 
{
    public int Id { get; set;}
    public string Nome { get; set;}

    public virtual ICollection<Pedido> Pedidos {get; set;}
}

public class Pedido
{
    public int Id { get; set;}
    public int PedidoId {get; set;}
    public DateTime Data {get; set;}

    public virtual Cliente Cliente {get; set;}
}

EF works with conventions, so if you speak ENTITY+ID (Clienteid, Pedidoid), but this is for another question. If you want to map at hand, it is also simple, in the order mapping class include;

public class PedidoMap : EntityTypeConfiguration<Pedido>
{
    public PedidoMap()
    {
        ToTable("Pedidos");

        HasRequired(x => x.Cliente)
            .WithMany(x => x.Pedidos)
            .HasForeignKey(x => x.PedidoId);
    }
}

Browser other questions tagged

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