Primary key convention for model class

Jan 30, 2011 at 12:37 AM
Edited Jan 30, 2011 at 12:44 AM

This error occurs when scaffolding the model class below:

Get-PrimaryKey : Cannot find primary key property for type 'PlayWithMVC3.Models.Course'. Multiple properties appear to be primary keys: pkid, CourseId  At  C:\...\packages\MvcScaffolding.0.9.4\tools\Controller\MvcScaffolding.Controller.ps1:59 char:29

public class Course {
    [Key]
    public int pkid { get; set; }
    public string CourseId { get; set; }
}

This is reasonable based on your conventions of {Model}Id. However I wonder if you could allow us to specify the convention somehow.
For example, here's how I do it for EF (I no longer need the [Key] attribute with the following code):

public class PlayWithMVC3Context : DbContext 
{
    protected override void OnModelCreating(ModelBuilder modelBuilder) {
        modelBuilder.Conventions.Add<PrimaryKeyConvention>();
    }

    internal class PrimaryKeyConvention : IConfigurationConvention<Type, EntityTypeConfiguration>
    {
        public void Apply(Type typeInfo, Func<EntityTypeConfiguration> configuration) {
            var pk = typeInfo.GetProperty("pkid");
            if (pk != null) {
                configuration().Key(pk);
            }
        }
    }
}

Dec 25, 2012 at 3:18 AM

I have the same issue while coding/scaffolding up