Testing framework says entity has no key defined for built in entity

风格不统一 提交于 2019-12-09 15:59:08

问题


Castle.Proxies.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.  

I am trying to setup tests for my MVC 5.1 project which uses EntityFramework version 6.1, AspNet.Identity.Core version 2.0, AspNet.Identity.EntityFramework version 2.0. My only test case is very simple and it is erroring with the above error for 'IdentityUserLogin' and for Entity Type 'IdentityUserRole' as soon as I try to run. The problem is that as far as I understand there are keys defined for both of these entities! As they are provided by the framework. I can't see explicitly their description in my code first portion but in the database I can see they both have keys.

In my test project I'm using Microsoft.VisualStudio.TestTools.UnitTesting and Moq (as well as the EF & Identity Core libs).

Any help or just pointing to resources would be much appreciated. I couldn't find anyone having a similar error.


回答1:


I had the same Problem and was finally able to get the test running by creating the mock as follows:

var mockContext = new Mock<MyDbContext>() { CallBase = true };

As I understand it, the Mock otherwise does not call base class implementations. And those Keys will probably be defined in the base class implementation of - I guess - OnModelCreating.




回答2:


In the Entity Framework, entities need to have a property (database column) defined as the primary key and it looks like you do not have one in your database (or EF does not properly map it).

To manually define a Key, you can use the Key attribute:

class IdentityUserLogin 
{
    [Key]
    public int IdentityUserLoginId { get; set; }
}


来源:https://stackoverflow.com/questions/22907581/testing-framework-says-entity-has-no-key-defined-for-built-in-entity

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