2015-04-01 112 views
0

我使用實體框架時,出現以下錯誤:實體框架的關係錯誤

Unable to determine the principal end of an association between the types 
'xxx.Domain.Entities.UserSettings' and 'xxx.Domain.Entities.User'. The 
principal end of this association must be explicitly configured using either 
the relationship fluent API or data annotations. 

這裏有兩個實體類:

public class User 
{ 
    [Key, Column("un")] 
    public string Username { get; set; } 
    public int Level { get; set; } 

    public virtual UserSettings UserSettings { get; set; } 
} 

public class UserSettings 
{ 
    [Key] 
    public string Username { get; set; } 
    public int ActiveRefresh { get; set; } 

    [ForeignKey("Username")] 
    public virtual User User { get; set; } 
} 

我不知道如何解決這個錯誤。我堅持數據庫設計,所以我無法更新,以解決問題。有沒有使用Fluent Api來讓這些關聯起作用的方法?

用戶可以擁有UserSettings對象。這是所期望的關係。

+0

只是一個想法:在'ForeignKey的(「用戶」),「用戶」'不似乎沒有匹配的東西? – renakre 2015-04-01 12:45:08

+1

這兩個實體之間想要什麼類型的關係?是的,Fluent Api可以完成所有註釋和更多功能。見[這裏](https://msdn.microsoft.com/en-us/data/jj591620) – 2015-04-01 12:55:00

+0

@PeterSmith用戶可以有一個UserSettings對象。這是所期望的關係。目前的設置令EntityFramework混淆。我也更新了這個問題。 – 2015-04-01 12:58:48

回答

2

它看起來像你需要一到零或一的關係

// Configure the primary key for the User 
modelBuilder.Entity<User>() 
    .HasKey(t => t.Username); 

// Map one-to-zero or one relationship 
modelBuilder.Entity<UserSettings>() 
    .HasRequired(t => t.User) 
    .WithOptional(t => t.UserSettings); 

這不是測試!刪除實體類中的所有註釋。在我上面的評論中鏈接到Fluent API relationships有更多關於不同種類關係的例子。

+0

這就是我最終使用的。感謝您的幫助。 – 2015-04-01 13:52:36

0

使用anotations:

public class User 
{ 
    [Key, Column("un")] 
    public string Username { get; set; } 
    public int Level { get; set; } 
    //here is your foreign to UserSettings 
    public int? UserSettingsID{ get; set; } 

    [ForeignKey("UserSettingsID")] // not needed if you're using the '%ID' convention 
    //Navigation property 
    public virtual UserSettings UserSettings { get; set; } 
} 

public class UserSettings 
{ 
    //UserSettings PK 
    public int UserSettingsID{ get; set; } 
    public int ActiveRefresh { get; set; } 
} 

我這裏假設你不需要從他設置檢索用戶