c# - 无法确定类型之间关联的主体端 - Entity Framework 错误,同一类之间的类关系

标签 c# .net entity-framework asp.net-mvc-4

有下面的类,并尝试在数据库中查找记录返回错误。 使用 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/

相关文章:

c# - 使用静态类访问全局/静态字典时有什么问题吗?

C#/.NET : Detect whether program is being run as a service or a console application

java - 从 JVM 调用 CLR 代码

c# - 使用 Entity Framework 创建动态查询

javascript - 在 javascript 中打印 C# TimeSpan 值

c# - 你如何测试枚举标志组合?

entity-framework - Entity Framework 中的可选列

asp.net-mvc - 使用 EF 6 和 MVC 5 中的代码优先方法将新表添加到现有数据库

c# - 将项目添加到列表,但不会按字母顺序排序

.net:分配对象引用是原子的(即线程安全的)吗?