简体   繁体   English

如何在EF-Code-First中指定主键名称

[英]How to Specify Primary Key Name in EF-Code-First

I'm using Entity Framework Codefirst to create my Database. 我正在使用Entity Framework Codefirst来创建我的数据库。 The default Primary key with the schema name dbo.pk_Jobs seems to upset access 2007 when I connect to it over ODBC. 当我通过ODBC连接到它时,具有模式名称dbo.pk_Jobs的默认主键似乎扰乱了访问2007。 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. 如果我手动编辑名称并删除模式名称并将此主键重命名为pk_jobs,则Access现在可以读取该表。

Can I specify the Primary Key name to not include the name of the schema using Fluent Api, Data Attributes or any other method. 是否可以使用Fluent Api,数据属性或任何其他方法指定主键名称不包括架构的名称。

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; }
}

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 使用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'");
    }
}

You can use the Key attribute to specify the parts of the primary key. 您可以使用Key属性指定主键的各个部分。 So your Job class might be 所以你的Job类可能是

public class Job
{
    [Key]
    public Guid uuid{ get; set; }
    public int active{ get; set; }
}

The data annotation attributes are defined in the System.ComponentModel.DataAnnotations namespace 数据注释属性在System.ComponentModel.DataAnnotations命名空间中定义

If I understand, you are asking how to change the name of the primary key column used by Entity Framework. 如果我理解,您询问如何更改Entity Framework使用的主键列的名称。 The following addition to your HasKey statement should take care of this: 以下对HasKey语句的补充应该注意这一点:

modelBuilder.Entity<Job>().Property(j => j.uuid).HasColumnName("pk_Jobs")

(This is a complement to the answer/comments by @Jeff Sivers and @cubski.) (这是@Jeff Sivers和@cubski的答案/评论的补充。)

As far as I know you can't specify the PK name with Data Attribute. 据我所知,您无法使用数据属性指定PK名称。 Sometimes I need to get rid of the dbo. 有时我需要摆脱dbo. part of the name and I then use a manually edited code first migration to change the name, like this: 部分名称然后我使用手动编辑的代码首次迁移来更改名称,如下所示:

public partial class ChangeNameOnPKInCustomers : DbMigration
{
    private static string fromName = "PK_dbo.Customers";    // Name to change

    private static string toName = fromName.Replace("dbo.", "");

    public override void Up()
    {
        Sql($"exec sp_rename @objname=N'[dbo].[{fromName}]', @newname=N'{toName}'");
        // Now the PK name is "PK_Customers".
    }

    public override void Down()
    {
        Sql($"exec sp_rename @objname=N'[dbo].[{toName}]', @newname=N'{fromName}'");
        // Back to "PK_dbo.Customers".
    }
}

When you add an explicit migration using Code First, you get a .cs file with the name of the migration which is a partial class with a base class DbMigration. 使用Code First添加显式迁移时,会得到一个带有迁移名称的.cs文件,该文件是具有基类DbMigration的分部类。

For your Primary Key Constraint, you have either DropPrimaryKey or AddPrimaryKey function depending on what you are trying to do. 对于主键约束,您可以使用DropPrimaryKey或AddPrimaryKey函数,具体取决于您要执行的操作。 My problem was with DropPrimaryKey as my Db had different name for the Primary Key. 我的问题是使用DropPrimaryKey,因为我的Db具有不同的主键名称。

Both these functions have overloads to take the name of the PK so that you could explicitly specify the name of the PK. 这两个函数都有重载来获取PK的名称,以便您可以显式指定PK的名称。 Worked fine for me for DropPrimaryKey with explicit PK name. 对于具有显式PK名称的DropPrimaryKey,我工作得很好。 The argument being object anonymousArguments which is by default null. 对象anonymousArguments的参数默认为null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM