本文介绍了无法确定类型之间关联的主要终点-实体框架错误,同一类之间的类关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
具有下面的类,并尝试在数据库中查找记录,返回错误.使用C#,MVC 4,实体框架4和SQL Server 2012数据库.
Have the class below, and try to look for records in the database returns error.Using C #, MVC 4, Entity Framework 4 and SQL Server 2012 database.
Unable to determine the principal end of an association between the types 'FlexApp.Models.Model.Usuario' and 'FlexApp.Models.Model.Usuario'.
The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
课程
public class Usuario
{
[Key]
public int UsuarioID { get; set; }
public string Nome { get; set; }
public int UsuCad { get; set; }
public int UsuAlt { get; set; }
[ForeignKey("UsuCad")]
public virtual Usuario UsuarioCad { get; set; }
[ForeignKey("UsuAlt")]
public virtual Usuario UsuarioAlt { get; set; }
}
数据库FK
alter table USUARIO add constraint USUARIO_fk01 foreign KEY(UsuCad) REFERENCES USUARIO(UsuarioID);
alter table USUARIO add constraint USUARIO_fk02 foreign KEY(UsuAlt) REFERENCES USUARIO(UsuarioID);
推荐答案
回复
经过大量搜索后,我发现了有关使用InverseProperty
的提示然后代码看起来像这样.该属性ForeignKey
用于安装链接,而属性InverseProperty
用于通知该字段依赖于另一个阵营,从而反转外键.
reply
After searching a lot, I found a tip about using InverseProperty
Then the code looks like this. This property ForeignKey
It is to mount the link and property InverseProperty
for to inform that the field depends on this other camp, reversing the foreign key.
感谢您的帮助
public class Usuario
{
[Key]
public int UsuarioID { get; set; }
public string Nome { get; set; }
public int UsuCad { get; set; }
public int UsuAlt { get; set; }
[ForeignKey("UsuCad")]
[InverseProperty("UsuarioID")]
public virtual Usuario UsuarioCad { get; set; }
[ForeignKey("UsuAlt")]
[InverseProperty("UsuarioID")]
public virtual Usuario UsuarioAlt { get; set; }
}
这篇关于无法确定类型之间关联的主要终点-实体框架错误,同一类之间的类关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!