EntityFramework using wrong tablename

六眼飞鱼酱① 提交于 2019-12-04 02:38:54
Jin-Wook Chung

For the database-first approach, StriplingWarrior's solution works well. But if you use the code-first approach, you could use System.ComponentModel.DataAnnotations.TableAttribute on a target entity class to map an entity class to a database table.

However, this way is slightly annoying, because we commonly want to define a pure entity class. To do this, you could entrust it to another class or use the overrided OnModelCreating method in the DbContext class as the following.

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Category>()
        .ToTable("MyCategories");
    }

Decorate your entity class with the TableAttribute property, e.g.

[Table("Bieren")]

Your Entity Framework model has information about the table names and connections that it is connecting to. If you're using a database-first approach, you should have an EDMX file with your database model in it. The easiest way is to update the model from the database.

  1. Open the EDMX file in Visual Studio
  2. Delete the incorrect "Biers" table
  3. right-click in the background and click "Update Model from database"
  4. Point the wizard at your database, and select the "Bieren" table to add
  5. Finish the wizard, and the "Bieren" table should appear

It is also possible to dig into the properties of the Biers type, and manually change the table name.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!