2017-08-02 35 views
0

EF.core初學者在這裏。 在我的應用程序中,我有人。這些連接到其他人(在同一張表中),並且這些連接具有「級別」。我添加了一個名爲連接的連接表,用於存儲誰連接到誰以及在什麼級別。當試圖做一個附加的遷移,我收到以下錯誤:EF.core一對多引用同一張表

Unable to determine the relationship represented by navigation property 'Connection.Person' of type 'Person'. Either manually configure the relationship, or ignore this property from the model.

還有我的其他沒有問題的加入引用兩個不同的表的表。我在這裏錯過了什麼?

我使用EF.core 1.1,與.NET 4.5,下面的代碼

public class Person 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public string NickName { get; set; }       
    public List<Connection> Connections { get; set; } 
} 

public class Connection 
{ 
    public int PersonId { get; set; } 
    public Person Person { get; set; } 
    public int SecondPersonId { get; set; } 
    public Person SecondPerson { get; set; } 
    public int ConnectionLevelId { get; set; } // connection Level 
    public ConnectionLevel Level { get; set; } 
} 

public class ConnectionLevel 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    //rights 
} 

public class testContext : DbContext 
{ 
    public DbSet<Person> Persons { get; set; } 
    public DbSet<Connection> Connections { get; set; } 
    public DbSet<ConnectionLevel> ConnectionLevels { get; set; } 

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 
    { 
     optionsBuilder.UseSqlServer("Server=localhost\\SQLEXPRESS;Database=master;Trusted_Connection=True;"); 
     base.OnConfiguring(optionsBuilder); 
    } 

    protected override void OnModelCreating(ModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<Connection>().HasKey(s => new { s.PersonId, s.SecondPersonId }); 
     base.OnModelCreating(modelBuilder); 
    } 
} 
+1

是Person.Connection列表的PersonId,或由SecondPersonId引用當前人?這就是錯誤所要求的。 –

+0

如何告知EF Person.Connections是指PersonId是我的下一個問題:) –

+1

使用'InverseProperty'屬性或流利的API。請參閱[關係](https://docs.microsoft.com/en-us/ef/core/modeling/relationships) –

回答

0

我認爲你必須映射關係,指定外鍵的類之間,就像這樣:

modelBuilder.Entity<Connection>().HasOne(t => t.Person) 
      .WithMany(t => t.Connections) 
      .HasForeignKey(d => d.PersonId); 

modelBuilder.Entity<Connection>().HasOne(t => t.SecondPerson) 
      .WithMany(t => t.Connections) 
      .HasForeignKey(d => d.SecondPersonId); 

我希望這有助於。

+0

這不會奏效。您不能將2個FK映射到一個集合。 –