Trouble with Keys

I’ve just spent a couple of hours scratching my head with database/entity framework problem.

My client has a requirement to duplicate records from one database to another when the first is updated.

The tables were identical and based on a class inherited from the IdentityUserRole class, with another field added to the composite key.  However, although data saved OK into the original database, an error was being thrown when trying to duplicate the records into the second database.

After some debugging, I found out that it was an issue with the primary key. It wasn’t recognising the composite key.

The quick fix was to add the following into the dbContext class, in the OnModelCreating method:

modelBuilder.Entity<ApplicationUserTeamRole>().ToTable("AspNetUserRoles")
 .HasKey(x=>new{x.RoleId,x.UserId, x.TeamId});

Everything immediately started working.

Advertisements

About John

Software developer, lately specialising in Full Stack Web Development using c#, ASP.Net WebAPI 2, and Angular.
This entry was posted in Development, EntityFramework and tagged . Bookmark the permalink.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s