Skip to main content
 首页 » 编程设计

c#之Entity Framework 外键问题

2024年02月13日12over140

首先,我只想声明我确实经常看到这个问题。我知道可能存在重复,但我已经搜索和搜索了,但没有找到正确的解决方案。

 public class Members 
{ 
    public enum Statuses 
    { 
        APPLIED, 
        ACTIVE, 
        SUSPENDED, 
        DELETED 
    } 
 
    [Key] 
    public int ID { get; set; } 
    [Required] 
    public string UName { get; set; } 
    public int RecruiterID { get; set; } 
    public int AuditorID { get; set; } 
    public virtual ICollection<AuditorComments> AuditorComments { get; set; } 
    [Required] 
    public Statuses Status { get; set; } 
    [Timestamp] 
    public Byte[] Timestamp { get; set; } 
 
    [ForeignKey("RecruiterID")] 
    public virtual Members Recruiter { get; set; } 
    [ForeignKey("AuditorID")] 
    public virtual Members Auditor { get; set; } 
} 

基本上我是不是把外键绑在一起了?

这是我收到的错误:

Unable to determine the principal end of an association between the types 
'tn.Data.Members' and 'tn.Data.Members'. The principal end of this association 
must be explicitly configured using either the relationship fluent API or data 
annotations. 

我还有许多其他类似的表,但如果我能让这个表正常工作,那么我就能修复它们。

请您参考如下方法:

我会更简洁地使用这些关系的流利规范,因为它们更整洁,让实际的类更容易阅读。 POCO 和 IMO。

另一方面,您所描述的结构对于 SQL 实际上是不可能的,因为 Members 需要 Members,这意味着您无法引导您的模型,并且它始终会包含循环。

这里是您如何使用流畅的配置来做到这一点。

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
    modelBuilder.Entity<Members>() 
        .HasOptional(m => m.Auditor) 
        .WithMany() 
        .HasForeignKey(p => p.AuditorId); 
 
    modelBuilder.Entity<Members>() 
        .HasOptional(m => m.Recruiter) 
        .WithMany() 
        .HasForeignKey(p => p.RecruiterId); 
} 

有关如何在 EF 中使用导航属性的更多详细信息,请在此处查看我的文章:http://blog.staticvoid.co.nz/2012/7/17/entity_framework-navigation_property_basics_with_code_first