如何使用自我表关系? [英] How to work with self table relationship?

查看:72
本文介绍了如何使用自我表关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的自我关系的表:


树(IDNode,IDRootNode,...)


IDRootNode是IDNode的链接。我有特殊情况,其中rootNode,列IDRootNode本身。


IDNode是一个bigint自动数字。


当我尝试创建时一个新的根节点我这样做:

 Trees myRootNode = new Trees(); 

myRootNode.RootNode = myRootNode;

SaveChanges();

问题是我收到一条错误消息:无法确定相关操作的有效排序。由于外键约束,模型需求或存储生成的值,可能存在依赖关系。


可能的解决方案是使用aditional SaveChanges()获取IDNode,然后将节点指定为rootNode然后做一个新的SaveChanges()。


但我想知道是否有更好的解决方案,而不是使用两个SaveChanges()。




非常感谢你。

解决方案

你好ComptonAlvaro,


实体框架支持自引用外键。你没有提到你正在使用什么,数据库优先或代码优先?所以我提供了两个关于这个问题的方法。


如果您使用的是Database First,请在数据库中添加一个自我参考,然后在外键中添加,然后在您的项目中刷新EF,EF将使一切准备就绪。


如果您使用的是Code First,请尝试以下链接中的代码段
http://stackoverflow.com/questions/4811194/what-is-the-syntax-for -self-referencing-foreign-key-in-ef-code-first


我希望它有所帮助。


问候,< a href ="http://stackoverflow.com/questions/4811194/what-is-the-syntax-for-self-referencing-foreign-keys-in-ef-code-first">


I have a table that has a self relationship like that:

Tree(IDNode, IDRootNode, ...)

Where IDRootNode is a link to IDNode. I have the particular case, in which the rootNode, the column IDRootNode is itself.

IDNode is a bigint autonumeric.

When I try to create a new root node I do that:

Trees myRootNode = new Trees();

myRootNode.RootNode = myRootNode;

SaveChanges();

The problem is that I get an error that says: unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constrainsts, model requierements or store-generated value.

A possible solution is to use an aditional SaveChanges() to get the IDNode and then assign the node as rootNode and do a new SaveChanges().

But I am wondering if there is a better solution instead of use two SaveChanges().

Thank you so much.

解决方案

Hi ComptonAlvaro,

Entity framework supports self-referencing foreign keys. You don't mention what you are using, database first or code first? So I provides two approaches about the issue.

If you are using Database First, please add a self-referenc and then in foreign key in your database and then refresh EF in your project, EF will make everything ready.

If you are using Code First, try the code snippet in the following link http://stackoverflow.com/questions/4811194/what-is-the-syntax-for-self-referencing-foreign-keys-in-ef-code-first

I hope it helps.

Regards,


这篇关于如何使用自我表关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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