0

I have a simple Many to Many relationship in using C# .net Core 6 EF asp.net project.

public class PageTag // : BaseEntity
    {
        [Key]
        [Column(Order =1)]
        public int TagId { get; set; }
        [Key]
        [Column(Order =2)]
        public int PageId { get; set; }
        public virtual Page? Page { get; set; }
        public virtual Tag? Tag { get; set; }
    }

As you can see, I have set the column order for the composite key. But when I try to do a search against it, the keys are backwards in their order.... for instance if i call the method:

GetAsync(pageTagVM.TagId, pageTagVM.PageId);

The Find will not work unless I reverse the order to:

GetAsync(pageTagVM.PageId, pageTagVM.TagId);

----- calls below method -----

 public async Task<T?> GetAsync(int? id1, int? id2)
        {
            if (id1 == null || id2 == null)
            {
                return null;
            }
            var geterdone =  await context.Set<T>().FindAsync(id1, id2);
            return geterdone;
        }

Is there some way to specify what order the variables are checked in? I would have to remember each time to reverse these in order to get the outcome. Am I even doing this the right way? It feels like the way it's setup, it's kind of like a loosely typed variable, so if a mistake is made, and someone writes it backwards, there would be no way at compile time to check which variable should go first or 2nd. How can I specify which one comes first or second in the dbcontext.Set method? I basically had to test it until i found out which order to use, i assumed ColumnOrder would take care of that in the model, but apparently it doesn't.

Ricky
  • 840
  • 1
  • 8
  • 11

1 Answers1

0

AS @svyatoslav-danyliv said, i found OnModelCreating and assigned the keys as below inside the ApplicationDbContext class:

protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            builder.Entity<PageTag>()
                .HasKey(pt => new { pt.PageId, pt.TagId });
            builder.Entity<PageTag>()
                .HasOne(pt => pt.Page)
                .WithMany(pt => pt.PageTags)
                .HasForeignKey(pt => pt.PageId); 
            builder.Entity<PageTag>()
                .HasOne(pt => pt.Tag)
                .WithMany(pt => pt.PageTags)
                .HasForeignKey(pt => pt.TagId); 
        }
Ricky
  • 840
  • 1
  • 8
  • 11