Search code examples
asp.net-core-mvcdatacontextasp.net-core-webapi

How to use one database in two .Net core MVC and Web API projects?


I've create two MVC and Web API .Net Core projects in one solution, in first project i've added model Phone and DataContext for it, made migration and update-database. In second project i've added equals connectionstring,model and DataContext, but when i try make the update-database i get the next error:

There is already an object named 'Phones' in the database.

Tell me please the right way how to configure database, datacontext and models in two projects to use one database ?


Solution

  • If you use two separate DbContexts, each with their own migrations, they'll consider the database to be theirs and reapply the changes that the other project already did, resulting in conflicts such as the one you observed.

    Simply move the Entity Framework code into a shared class library and reference that library from both implementing projects, so all state about the database is shared.