【问题标题】:How do I link two properties to one class but only being able to reference to one in EFC Code First?如何将两个属性链接到一个类,但只能在 EFC Code First 中引用一个?
【发布时间】:2019-03-11 09:41:34
【问题描述】:

我有两个班级:

public class User
{
    public Guid UserId { get; set; }
    [Required]
    public string Username { get; set; }
    [Required]
    public string Password { get; set; }

    public UserProfile UserProfile { get; set; }
}

public class UserProfile
{
    public int UserProfileId { get; set; }
    public string Avatar { get; set; }

    public User User { get; set; }
    public User Wingman { get; set; }
}

尝试添加迁移可以理解,但出现以下错误:

无法确定导航所代表的关系 “UserProfile”类型的属性“User.UserProfile”。要么手动 配置关系,或使用 '[NotMapped]' 属性或使用 'EntityTypeBuilder.Ignore' 'OnModelCreating'。

UserProfile.User 是用户本身,UserProfile.Wingman 是另一个用户,代表僚机。 我需要另一张桌子,比如一座桥,还是有其他方法可以解决这个问题? 而且我不需要从User 中引用Wingman

提前致谢!

【问题讨论】:

    标签: c# asp.net-core ef-code-first entity-framework-core


    【解决方案1】:

    您可以将InversePropertyAttribute 或Fluent API 配置方法HasOne/WithOneHasOne/WithMany 与适当的属性选择器一起使用。

    如果您正在寻找 1:1 关系,请使用分片主键 - 将 UserProfile 的 PK 设为 User 的 FK。

    modelBuilder.Entity<UserProfile>()
        .HasOne( up => up.User )
        .WithOne( u => u.UserProfile )
        .HasForeignKey( up => up.UserProfileId ); // I suggest renaming PK to UserId for clarity
    

    如果是1:N关系,两种方式;首先,InversePropertyAttribute:

    public class User
    {
        ...
        [InverseProperty( "User" )]
        public ICollection<UserProfile> UserProfiles { get; set; }
    }
    

    或通过 Fluent API:

    modelBuilder.Entity<UserProfile>()
        .HasOne( up => up.User )
        .WithMany( u => u.UserProfiles );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多