实体框架代码优先-更改表名称 [英] Entity Framework Code First - Changing a Table Name

查看:98
本文介绍了实体框架代码优先-更改表名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想先更改使用实体框架代码生成的表之一的名称。

I want to change the name of one of my tables generated using Entity Framework code first.

我已经创建了数据库,但是现在我想更改名称。我已将项目中对元数据 表的所有引用更新为元数据 。但是,数据库中正在生成的表仍然是元数据。我删除并重新创建了数据库,但这似乎也不起作用。都不使用TableAttribute。我该怎么办?

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. But the table that is being generated in the database is still "Metadatas". I've dropped and re-created the database, but that doesn't seem to work either. Neither does using a TableAttribute. What I'm I supposed to do?

谢谢。

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

...

推荐答案

这里有两个选项-

数据注释:

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

或我们拥有Fluent Api:

or we have Fluent Api:

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

如果要确保域模型,最好使用Fluent Api保持整洁。

Using the Fluent Api is the preferred option if you want to ensure your Domain Model stays uncluttered.

此外,如果您只想删除表名的复数形式,则可以使用以下代码覆盖EF的功能: :

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:

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

这篇关于实体框架代码优先-更改表名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆