I’m working with the Entity Framework and I’m having a problem:
When I try to insert some data in a table it tells me that it’s violating integrity of reference but the other table is normally populated and has the value i’m trying to insert.
Pedido pedido = new Pedido();
pedido.Data = DateTime.Now;
db.AddToPedido(pedido);
db.SaveChanges();
EntityKey chave = db.CreateEntityKey("Pedido", pedido);
Itens_Pedido item = new Itens_Pedido();
item.Pedido_Id = Convert.ToInt32(chave.EntityKeyValues.First().Value);
item.Carta_Id = Convert.ToInt32(Request.QueryString["Id"].ToString());
item.Quantidade = 1;
item.Foil = "N";
db.AddToItens_Pedido(item);
db.SaveChanges();
I think I know what is going on.
If you have an identifying relationship between
PedidoandIten_Pedidoi.e. the Primary Key of
Iten_Pedidois a compound and made up of two fields one of which is an FK back to Pedido (that would be thePedido_Id) in your case, unfortunately you can’t build that relationship using thePedido_Idproperty you have to use thePedidonavigation property instead.If you have the
Pedidoalready in the context all you need to do is build the relationships as normal. If however it isn’t int the context, which I suspect, and all you know is the key, then you have two options:1) Query for it
2) Fabricate a stand-in entity and attach it (this is similar to a query in that it puts the entity in the ObjectContext in the unchanged state).
So the patterns are either:
or
See my tips series for more information, in particular tip 9
Hope this helps
Alex