views:

661

answers:

1

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

+1  A: 

I think I know what is going on.

If you have an identifying relationship between Pedido and Iten_Pedido

i.e. the Primary Key of Iten_Pedido is a compound and made up of two fields one of which is an FK back to Pedido (that would be the Pedido_Id) in your case, unfortunately you can't build that relationship using the Pedido_Id property you have to use the Pedido navigation property instead.

If you have the Pedido already 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:

//assuming the key of the Pedido is Id change as appropriate
Pedido pedido = ctx.Pedido.First( p => p.Id == XXX); 
item.Pedido = pedido;
...
ctx.AddToItens_Pedido(item);
ctx.SaveChanges();

or

Pedido pedido = new Pedido {Id = XXX};
ctx.AttachTo("Pedido", pedido);
item.Pedido = pedido;
...
ctx.AddToItens_Pedido(item);
ctx.SaveChanges();

See my tips series for more information, in particular tip 9

Hope this helps

Alex

Alex James
@Alex can you please look at this http://stackoverflow.com/questions/1158795/
Binoj Antony