2015-04-01 117 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; } 
} 

我这里假设你不需要从他设置检索用户