简体   繁体   English

实体框架代码优先 - 更改表名称

[英]Entity Framework Code First - Changing a Table Name

I want to change the name of one of my tables generated using Entity Framework code first. 我想先更改使用Entity Framework代码生成的其中一个表的名称。

I have already created the database, but now I want to change the name. 我已经创建了数据库,但现在我想更改名称。 I've updated all references to the "Metadatas" table to "Metadata" in my project. 我在项目中将所有对"Metadatas"表的引用更新为"Metadata" But the table that is being generated in the database is still "Metadatas". 但是在数据库中生成的表仍然是“Metadatas”。 I've dropped and re-created the database, but that doesn't seem to work either. 我已经删除并重新创建了数据库,但这似乎也没有用。 Neither does using a TableAttribute. 也没有使用TableAttribute。 What I'm I supposed to do? 我该怎么办?

Thanks. 谢谢。

[Table("Metadata")]
public class Metadata 
{
    [Required, Key]
    public int MetadataId { get; set; }

    [Required, ScaffoldColumn(false)]
    public int DocumentId { get; set; }

    [Required, StringLength(250), DataType(DataType.Text)]
    public string Title { get; set; }

... ...

You have two options here- 你有两个选择 -

Data Annotations: 数据注释:

//Changing database table name to Metadata
[Table("Metadata")]
public class Metadata 
{
  [Required, Key]
  public int MetadataId { get; set; }

  [Required, ScaffoldColumn(false)]
  public int DocumentId { get; set; }

  [Required, StringLength(250), DataType(DataType.Text)]
  public string Title { get; set; 
}

or we have Fluent Api: 或者我们有流利的Api:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  //Changing Database table name to Metadata
  modelBuilder.Entity<Metadata>()
      .ToTable("Metadata");
}

Using the Fluent Api is the preferred option if you want to ensure your Domain Model stays uncluttered. 如果要确保域模型保持整洁,则使用Fluent Api是首选选项。

Just adding to this, if you solely want to remove the pluralisation of your table names, you can override EFs ability to do so with the following line of code: 只是添加到此,如果您只想删除表名的复数,则可以使用以下代码行覆盖EF的功能:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}

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

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