Using Foreign Keys with different Contexts using Entity Framework code-first

雨燕双飞 提交于 2019-12-11 12:35:09

问题


I have a brand-new ASP.NET MVC 5 project with one DbContext using Entity Framework 6.1 and Identity 2.2.1. Trying go use IoC, I created a 2nd DbContext and some classes belonging to that 2nd context.

Most of these classes have a foreign key to the IdentityUser class within Identity 2.2.1. The problem I'm having is that when I try to use Add-Migrations I get the following error:

One or more validation errors were detected during model generation:

{MyProjectName}.DataContexts.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.

{MyProjectName}.DataContexts.IdentityUserRole: : EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType.

IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' is based on type 'IdentityUserLogin' that has no keys defined.

IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based on type 'IdentityUserRole' that has no keys defined.

When I move the classes I created from my 2nd context into the initial context, I don't get any error and the database table build as expected.

How can I keep IoC AND have foreign key restrictions work properly with EF and CodeFirst?

Sample

You can find a sample project at https://github.com/RoLYroLLs/MultiDbContextForeignKeySample. To recreate the error run this on the Package Manager Console:

Enable-Migrations -MigrationsDirectory "DataContexts\ClientMigrations" -ContextTypeName MultiDbContextForeignKeySample.DataContexts.ClientDbContext

来源:https://stackoverflow.com/questions/34255335/using-foreign-keys-with-different-contexts-using-entity-framework-code-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!