Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

c# - 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.

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?

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

...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...