有下面的类,并尝试在数据库中查找记录返回错误。 使用 C#、MVC 4、Entity Framework 4 和 SQL Server 2012 数据库。
错误
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; }
}
数据库外键
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
用于通知该字段依赖于此另一阵营,反转外键。
感谢帮助
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; }
}
关于c# - 无法确定类型之间关联的主体端 - Entity Framework 错误,同一类之间的类关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33927415/