我想在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; }
}
列UserVisitorId
与User.UserID
没有关系。
答案 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)