Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Specify Primary Key Name in EF-Code-First

I'm using Entity Framework Codefirst to create my Database. The default Primary key with the schema name dbo.pk_Jobs seems to upset access 2007 when I connect to it over ODBC. If I manually edit the name and remove the schema name and rename this Primary Key to pk_jobs, Access can now read the table.

Can I specify the Primary Key name to not include the name of the schema using Fluent Api, Data Attributes or any other method.

public class ReportsContext : DbContext {     public DbSet<Job> Jobs { get; set; }     protected override void OnModelCreating(DbModelBuilder modelBuilder)     {         modelBuilder.Entity<Job>().ToTable("Jobs");         modelBuilder.Entity<Job>().HasKey(j => j.uuid);          base.OnModelCreating(modelBuilder);     } } public class Job {     public Guid uuid{ get; set; }     public int active{ get; set; } } 
like image 380
tourdownunder Avatar asked Nov 28 '12 14:11

tourdownunder


People also ask

How do I set primary key in Entity Framework?

Configuring a primary key By convention, a property named Id or <type name>Id will be configured as the primary key of an entity. Owned entity types use different rules to define keys. You can configure a single property to be the primary key of an entity as follows: Data Annotations.

What is meant by composite primary key in Entity Framework code First?

Use the ColumnAttribute or the HasKey method to specify an order for composite primary keys. In order to use composite keys, Entity Framework requires you to define an order for the key properties. You can do this by using the Column annotation to specify an order.


1 Answers

If you want to specify the column name and override the property name, you can try the following:

Using Annotations

public class Job {     [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]     [Column("CustomIdName")]     public Guid uuid { get; set; }     public int active { get; set; } } 

Using Code First

    protected override void OnModelCreating(DbModelBuilder mb)     {         base.OnModelCreating(mb);          mb.Entity<Job>()             .HasKey(i => i.uuid);         mb.Entity<Job>()           .Property(i => i.uuid)           .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)           .HasColumnName("CustomIdName");     } 

Inside Migration Configuration

public partial class ChangePrimaryKey : DbMigration {     public override void Up()     {         Sql(@"exec sp_rename 'SchemaName.TableName.IndexName', 'New_IndexName', 'INDEX'");     }      public override void Down()     {         Sql(@"exec sp_rename 'SchemaName.TableName.New_IndexName', 'Old_IndexName', 'INDEX'");     } } 
like image 114
cubski Avatar answered Sep 28 '22 14:09

cubski