Reputation: 5908
I need to manually enter primary key values in a database, as i need the key values to be in sync with an Enum. However using DatabaseGeneratedoption.None doesn't appear to work. Even when i delete the database and start fresh, the Id column in the JobType still has an auto-incrmeneting primary key.
Is it anything to do with the fact that i'm using an enum as a primary key?
Job Entity
public class Job : EntityBase
{
public long JobId { get; set; }
public JobTypeEnum JobTypeId { get; set; }
public JobType JobType { get; set; }
}
Job Type
public class JobType
{
public JobTypeEnum Id { get; set; }
public String Name { get; set; }
public String Description { get; set; }
}
Configuration Classes
public class JobTypeConfiguration : EntityTypeConfiguration<JobType>
{
public JobTypeConfiguration()
{
HasKey(x => x.Id);
Property(x => x.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
Property(x => x.Name).HasMaxLength(20);
Property(x => x.Description).HasMaxLength(255);
}
}
public class JobConfiguration : EntityTypeConfiguration<Job>
{
public JobConfiguration()
{
HasKey(x => x.JobId);
Property(x => x.JobId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
HasRequired(x => x.JobType).WithMany().HasForeignKey(x => x.JobTypeId);
}
}
Model Builder
modelBuilder.Configurations.Add(new JobConfiguration());
modelBuilder.Configurations.Add(new JobTypeConfiguration());
EDIT:
I've tracked down a probable cause. I have a Migration that creates tables for Elmah. If i exclude that migration, then it works fine. If i include it, then it doesn't.
Bizarre...
Upvotes: 5
Views: 8081
Reputation: 22595
I have taken your code and added it to my project. This is the Migration code generated:
public override void Up()
{
CreateTable(
"dbo.Jobs",
c => new
{
JobId = c.Long(nullable: false, identity: true),
JobTypeId = c.Int(nullable: false),
})
.PrimaryKey(t => t.JobId)
.ForeignKey("dbo.JobTypes", t => t.JobTypeId, cascadeDelete: true)
.Index(t => t.JobTypeId);
CreateTable(
"dbo.JobTypes",
c => new
{
Id = c.Int(nullable: false),
Name = c.String(maxLength: 20),
Description = c.String(maxLength: 255),
})
.PrimaryKey(t => t.Id);
}
You can see that the dbo.JobTypes
table does not have identity: true. You may find that you have fallen into the problem described here: How to alter column from DatabaseGenerated.Identity to DatabaseGenerated.None
The simplest thing to do is probably to find the CreateTable
statement for JobType
, fix it, then re-create the database.
Upvotes: 2