简体   繁体   中英

Entity Framework multiple relationships/navigations to entity type

I want to create this database schema in ASP.NET Core:

I already tried it with this code without success.

User

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

I'm getting this error on the migrations:

Unable to determine the relationship represented by navigation property >'User.Visitors' of type 'UserVisitors'. Either manually configure the >relationship, or ignore this property using the '[NotMapped]' attribute or >by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

I hope someone can help me. Thanks in advance.

Update:

Changed UserVisitors to:

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

I can compile it now, but on the database is it wrong. Database image:

The column UserVisitorId doesn't have a relationship to User.UserID .

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

Then you need to make proper mappings using OnModelCreatig as follows:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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