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!
– Gabriel Coletta