I am having a User Model and and a Group Model. User and Group share a many to many relationship. In when I translate this to table, I want to have a mapping table. I am using the following to achieve this.
modelBuilder.Entity<UserGroup>()
.HasMany(a => a.Users)
.WithMany(b => b.UserGroup)
.Map(mc =>
{
mc.ToTable("UserUserGroupMapping");
mc.MapLeftKey("UserId");
mc.MapRightKey("UserGroupId");
});
This creates a table with UserId and UserGroupId as columns. However I have few challenges,
I would like to be able to add an Identity column to this table and some audit columns (ex: Created by, created date) to the table. I am not sure how to do this.
Can any one help me here?
Thanks
I think it'll work if you do the following:
Add a mapping table and configure its table name to match the original table name.
Replace the many-to-many collection properties from
User
andUserGroup
and replace it with one-to-many associationsUse the package manager to
Add-Migration
and remove anything from the scaffolded migration that might attempt to drop the old table and create a new table. The migration will need to at least (I might be missing some here):DropPrimaryKey
for the original key columnsAddColumn
for the new columns (withInt(identity:true, nullable: false)
for the new primary key column)AddPrimaryKey
for the new key columnThen you can use the methods outlined in this answer to retrieve entities.