Cannot declare unconventional PK via Data Annotations for a MVC3 Entity Model
I'm trying to declare a Primary Key for an Entity Model that will eventually be consumed by ASP.NET MVC3 to create a Controller class, for that reason I'm decorating a value with the [Key]
attribute:
Foobar.cs
using System.ComponentModel.DataAnnotations;
public class Foobar
{
[Key]
public string Foo { get; set; }
public string Bar { get; set; }
}
FoobarDbContext.cs
using System.Data.Entity;
public class FoobarDBContext : DbContext
{
publ开发者_StackOverflow社区ic DbSet<Foobar> Foobars { get; set; }
}
Which when attempting to create the aforementioned Controller results in the following error:
---------------------------
Microsoft Visual Studio
---------------------------
Unable to retrieve metadata for 'Dotnet.Samples.AspNetMvc.Models.FoobarDBContext'.
One or more validation errors were detected during model generation:
- System.Data.Edm.EdmEntityType: : EntityType 'Foobar' has no key defined.
Define the key for this EntityType.
- System.Data.Edm.EdmEntityType: : EntityType 'FoobarDBContext' has no key defined.
Define the key for this EntityType.
- System.Data.Edm.EdmEntitySet: EntityType: EntitySet __Foobars__
is based on type ?Foo? that has no keys defined.
- System.Data.Edm.EdmEntitySet: EntityType: EntitySet __FoobarDBContexts__
is based on type __FoobarDBContext__ that has no keys defined.
---------------------------
OK
---------------------------
Any suggestion will be really appreciated. Thanks much in advance,
UPDATE
According to Data Annotations in the Entity Framework and Code First
KeyAttribute is used to specify that a property/column is part of the primary key of the entity and applies to scalar properties only.
Therefore I guess I'd have to go ahead and create a 'non-semantic' identifier such as FoobarID
in order to take advantage of the code generation functionality.
This shouldn't be necessary, I have a class User with the primary key defined as follows:
[Key]
public string UserName { get; set; }
and it works perfectly... Is there any other info about the class FooBar that might be relevant?
One other thing, a scalar property is "A property of an entity that maps to a single field in a storage schema", so it should not be a problem to try and use a string property as the PK. Not a very helpful remark, I know, but it sort of indicates that there's something else going on.
精彩评论