Longa
Longa

Reputation: 364

How to add second DbContext to existing EF project

I have an existing Ef DbContext (ApplicationDbContext) that connect to a MySql server with it's proper OnConfiguring and OnModelCreating function.

Now I must add a new DbContext (GeoDbContext) to a different server.

I add the GeoDbContext in services

.AddDbContext<ApplicationDbContext>(m => m.UseMySql(ApplicationConn, ServerVersion.AutoDetect(ApplicationConn)))
.AddDbContext<GeoDbContext>(m => m.UseNpgsql(GeoConn))

In the GeoDbContext, with its own OnConfiguring and OnModelCreating function, I defined a new DbSet property

public DbSet<UserLocation> Locations { get; set; }

Then I exec the Add-Migration , and this is my problem. Specifying I want to use the GeoDbContext

Add-Migration addLocation -Context GeoDbContext

I receive an error about properties existing in the ApplicationDbContext, already correctly configured in the ApplicationDbContext OnModelCreating function.

The entity type (omissed) has multiple properties with the [Key] attribute. Composite primary keys can only be set using 'HasKey' in 'OnModelCreating'.

I want add a migration only for the GeoDbContext. How to correctly configure it?

Upvotes: 0

Views: 152

Answers (1)

Longa
Longa

Reputation: 364

As @KirkWoll wrote in the comment

This usually happens because one or more of the entity types (i.e. UserLocation) has relationship properties (either single or collection) with types that are in the other database.

Remove the navigation property from the model did the work.

Upvotes: 1

Related Questions