实体框架到实体类型的多种关系/导航

时间:2019-04-14 16:37:34

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

我想在ASP.NET Core中创建此数据库架构:

我已经使用此代码尝试了成功,

用户

public class User : IdentityUser 
{
    public override string Id { get; set; }
    public virtual UserVisitors Visitors { get; set; }
}

UserVisitors

public class UserVisitors 
{
    public int Id { get; set; }
    public string UserId { get; set; }
    public string UserVisitorId { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public DateTime VisitTime { get; set; }

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

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

我在迁移中遇到此错误:

  

无法确定类型为“ UserVisitors”的导航属性>“ User.Visitors”所表示的关系。要么手动配置>关系,要么使用[[NotMapped]]属性忽略此属性,或者>通过使用'OnModelCreating'中的'EntityTypeBuilder.Ignore'。

我希望有人能帮助我。预先感谢。

更新:

UserVisitors更改为:

public class UserVisitors 
{
    public int Id { get; set; }
    [InverseProperty("User")]
    public string UserId { get; set; }

    [InverseProperty("User")]
    public string UserVisitorId { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public DateTime VisitTime { get; set; }

    public virtual User User { get; set; }
}

我现在可以编译它,但是在数据库上是错误的。 数据库映像:

UserVisitorIdUser.UserID没有关系。

1 个答案:

答案 0 :(得分:0)

public class User : IdentityUser 
{

    public override string Id { get; set; }

    public virtual ICollection<UserVisitor> UserVisitors { get; set; }
    public virtual ICollection<UserVisitor> UserVisitors2 { get; set; }
}

public class UserVisitor 
{

    public int Id { get; set; }

    [InverseProperty("User")]
    public string UserId { get; set; }

    public virtual User User {get; set;}
    public virtual User UserVisitor  {get; set;}

    [InverseProperty("User")]
    public string UserVisitorId { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public DateTime VisitTime { get; set; }

    public virtual User User { get; set; }
  }

然后,您需要使用OnModelCreatig进行正确的映射,如下所示:

modelBuilder.Entity<UserVisitor>()
    .HasOne(x => x.UserVisitor)
    .WithMany(x => x.UserVisitors)

modelBuilder.Entity<UserVisitor>()
    .HasOne(x => x.User)
    .WithMany(x => x.UserVisitors2)