2021年3月18日星期四

EF Core - many to many relationship use / access custom join table

I am trying to implement a many to many relationship.

public class TestContext : DbContext  {      public DbSet<User> Users { get; set; }      public DbSet<Book> Books { get; set; }      public DbSet<Own> Own { get; set; }        protected override void OnConfiguring(DbContextOptionsBuilder options) => options.UseSqlServer("Server=DESKTOP-BT4H8CA;Database=Test;Trusted_Connection=True");        protected override void OnModelCreating(ModelBuilder builder)      {          builder.Entity<Book>().HasOne(x => x.Author);            builder.Entity<User>()              .HasMany(x => x.OwnedBooks)              .WithMany(x => x.OwnedBy)              .UsingEntity(x => x.ToTable("Own"));            builder.Entity<Own>()              .HasKey(x => new {x.BookId, x.UserId});      }  }    public class User  {      [Key]      public int Id { get; set; }      public string Name { get; set; }      public List<Book> OwnedBooks { get; set; }  }    public class Own  {      public int UserId { get; set; }      public int BookId { get; set; }      public User User { get; set; }      public Book Book { get; set; }  }    public class Book  {      [Key]      public int Id { get; set; }      public int AuthorId { get; set; }      public User Author { get; set; }      public List<User> OwnedBy { get; set; } //Not really needed, but without it I can't create the join table "Own"      [NotMapped]      public int UsersReached; //Get this via the "Own" table  }  

I am struggling with accessing the join table "Own". I need it to get the amout of each Book that is sold, without completely loading the users. Thats why I dont want to use the auto generated one:

Cannot use table 'Own' for entity type 'BookUser (Dictionary<string, object>)' since it is being used for entity type 'Own' and potentially other entity types, but there is no linking relationship. Add a foreign key to 'BookUser (Dictionary<string, object>)' on the primary key properties and pointing to the primary key on another entity typed mapped to 'Own'.

Thanks in advance for your help!

https://stackoverflow.com/questions/66701161/ef-core-many-to-many-relationship-use-access-custom-join-table March 19, 2021 at 08:54AM

没有评论:

发表评论