技术:ASP.NET MVC3,实体框架4,多层应用程序
我有两个表以0到1的关系。一个副本可以有0个或一个pagamento,而pagamento只有一个副本。关联
当我创建一个新的Pagameto实体并添加到一个Dupliacata时,Duplicata的行保存在我的数据库中:
A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship.
波纹管图像显示带有一个Pagamento的实体Duplicata。关联
和带有错误的代码:
context.Duplicata.Attach(duplicata);
context.ObjectStateManager.ChangeObjectState(duplicata, EntityState.Modified);
context.SaveChanges();
是的,但是attach的用法不是将元素添加到重复副本中以使上下文脱离实体。如果要创建一个新的副本,只需创建一个新副本即可。像
// just for testing NO magic numbers!
var pagamentoId = 1;
var duplicata = new Duplicata();
duplicata.PAGAMENTO_ID = pagamentoId;
duplicata.VALOR = 1000;
duplicata.CLIENTE_ID = 23;
// add the rest of properties
// then...
context.AddObject("Duplicatas", duplicata);
context.SaveChanges();
注意,我在addobject中使用了“ Duplicatas”,因为我假设这是Duplicata集的名称(set表示它是Duplicata的集合,并且您在EDMX文件中设置了该名称)。
通过将pagamento_id设置为所需的值,它会自动生成两个实体之间的关系
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句