ASP Net Core: add many to many relationship with IdentityUser

后端 未结 2 1317
清酒与你
清酒与你 2021-01-06 13:31

i need to add a many to many relationship with UserIdentity in asp net core (i.e: a user can have many books and a book can have many user owners)

I have the book c

2条回答
  •  攒了一身酷
    2021-01-06 13:53

    Simple, public string ApplicationUserId { get; set; }

    ApplicationUser has a default key type of string.

    If you do want to use int, simple do:

    public class ApplicationUser : IdentityUser
    

    Be sure to declare this relationship in your DbContext.

    Here's a sample:

    entityTypeBuilder.HasKey(pcp => new { pcp.CurrencyPairId, pcp.IsMain })
                    .HasName("PartialCurrencyPair_CK_CurrencyPairId_IsMain");
    
                entityTypeBuilder.HasOne(pcp => pcp.Currency).WithMany(c => c.PartialCurrencyPairs)
                    .HasForeignKey(pcp => pcp.CurrencyId)
                    .HasConstraintName("PartialCurrencyPairs_Currency_Constraint");
                entityTypeBuilder.HasOne(pcp => pcp.CurrencyPair).WithMany(cp => cp.PartialCurrencyPairs)
                    .HasForeignKey(pcp => pcp.CurrencyPairId)
                    .HasConstraintName("PartialCurrencyPairs_CurrencyPair_Constraint");
    

    EDIT

    You don't have to explicitly define the generics together with the base class (IdentityUser). You simply do this:

    services.AddIdentity()
                    .AddEntityFrameworkStores()
                    .AddDefaultTokenProviders();
    

    This assumes Role and ApplicationUser share the same key type of string, where they are overloads of IdentityRole and IdentityUser respectively.

提交回复
热议问题