简体   繁体   English

实体框架关系错误

[英]Entity Framework Relationship Error

I get the following error when using Entity Framework: 使用实体框架时出现以下错误:

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.

Here are the two Entity classes: 这是两个实体类:

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; }
}

I am not sure how to resolve this error. 我不确定如何解决此错误。 I am stuck with the database design so I can't update that to fix the issue. 我坚持使用数据库设计,因此无法更新它以解决问题。 Is there a way using Fluent Api to get these associations working? 是否可以使用Fluent Api使这些关联正常工作?

A User can have a UserSettings object. 用户可以具有一个UserSettings对象。 This is the relationship that is desired. 这是所需的关系。

It looks like you need a one to zero-or-one relationship 看来您需要一对一或零对一的关系

// 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);

This is not tested! 这未经测试! Remove all the annotations from the entity classes. 从实体类中删除所有注释。 The link to Fluent API relationships in my comment above has more examples of the different kinds of relationship. 在我上面的评论中,与Fluent API关系的链接提供了有关不同类型关系的更多示例。

using 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; }
}

I assume here that you don't need to retrieve the user from his settings 我在这里假设您不需要从他的设置中检索用户

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM