C#无法确定关系的主要终点 [英] C# Unable to determine the principal end of the relationship

查看:59
本文介绍了C#无法确定关系的主要终点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

foreach (var item in order.MyFiles)
{
   var newFile = adapter.db.File.CreateObject();

   newFile.Name = item.FileName;

   adapter.db.File.AddObject(newFile);

   adapter.db.SaveChanges();

   item.MyFile.Add(new MyFile { FileID = newFile.FileID });

   adapter.db.SaveChanges();
}

foreach (var item in tempFilesList)
{
    adapter.db.DeleteObject(item);
}

adapter.db.SaveChanges();

该代码复制 MyFile 表中的行,例如,如果循环迭代3次,我会看到6行(3 x 2 * adapter.db.SaveChanges() ???)

That code duplicates rows in the MyFile table, e.g if the loop iterates 3 times I see 6 rows (3 x 2*adapter.db.SaveChanges() ???)

但是,如果我只有一个 adapter.db.SaveChanges(); (最后一个),我会得到错误

But, if I just have only one adapter.db.SaveChanges(); (that last one) I get the error

无法确定'my_dbModel.FK_MyFile_File'关系的主体结尾。多个添加的实体可能具有相同的主键。

我想是由于在这种情况下它没有提交 adapter.db.File.AddObject(newFile); 项,然后将其关联到 item.MyFile.Add(new MyFile {FileID = newFile.FileID}); 但是我可能错了,有什么办法解决它吗?

I suppose it is caused that in that case it doesn't commit the adapter.db.File.AddObject(newFile); items before assinging them to the item.MyFile.Add(new MyFile { FileID = newFile.FileID }); But I can be wrong, any ideas how to fix it?

推荐答案

您不能使用在保存更改之前定义新的 MyFile 时> newFile.FileID 。在将新实体保存到数据库之前,FileID为默认(0)。您必须在 MyFile 类中使用 File 的导航属性。 EF将检测到该关系并将适当地提交数据。

You cannot use newFile.FileID when defining a new MyFile before saving changes. The FileID is default (0) until you save the new entity in database. You'd have to use navigation property of File in your MyFile class. EF will detect the relation and will commit data appropriately.

尝试更改行 item.MyFile.Add(new MyFile {FileID = newFile.FileID});

item.MyFile.Add(new MyFile { File = newFile });  

其中 File 是在 MyFile 实体。

这篇关于C#无法确定关系的主要终点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆