Ef core create a index from two foreing keys

I want to create a index from two foreing keys. My probleme is since the key name is generated by windows the table product and the table user have the same PrimaryKey name Id

I have two class one for products and one for user

public class Product: EntityBase<Guid>

public class User : IdentityUser


builder.Entity<Rating>().HasIndex(r => new { r.User.Id, r.Product.Id }).HasName("IX_UserProductID").IsUnique(true);

Because the have the same name Id I get the following error.

An anonymous type cannot have multiple properties with the same name.

How can I best fix this probleme. Thank you for your help

1 answer

  • answered 2021-02-20 23:12 Junior Cortenbach

    I solved it by doing this

    First in my model Rating I added the following fields

        public string UserId { get; set; }
        public User User { get; set; }
        public Guid ProductID { get; set; }
        public Product Product { get; set; }

    And in MyDbCOntext I added this

        protected override void OnModelCreating(ModelBuilder builder)
             builder.Entity<Rating>().HasIndex(r => new { r.UserId, r.ProductID }).IsUnique(true);