Entity type does not contain any property marked with KeyAttribute
TheDevelolper opened this issue · comments
Hey so I was trying to use this with a model first generated edmx project.
I get the error:
System.InvalidOperationException: 'Entity type City does not contain any property marked with KeyAttribute'
City does indeed have an id which is marked as a key but looking at the entity I see this:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CityWeather.Data.Entities
{
using System;
using System.Collections.Generic;
public partial class City
{
public int Id { get; set; }
public string Name { get; set; }
}
}
So I can't seem to use your library for what I want to do it seems. Is that right? I'm guessing this is expecting a code first approach?
I managed to solve this myself by following the steps here:
https://stackoverflow.com/questions/16100418/entity-framework-5-does-not-generate-key-attribute
You can modify the way your EF files are generated. It's a bit hacky but good enough for me 👍
There is an overload of CreateDbSetMock
that let's you pass in a custom key factory which could be used in this case:
dbContextMock.CreateDbSetMock(x => x.Cities, (entity, _) => entity.Id);
If you don't pass a custom key factory, the default attribute-based key factory is being used which throws that exception you've mentioned.
Thank you for this! I'll change my code and re implement that today!