EntityFramework using wrong tablename

瘦欲@ 提交于 2019-12-05 19:39:29

问题


My code is giving me an EntityCommandExecutionException when i'm trying getting data from my Bieren Table.

The exception message says that it can't find "dbo.Biers" which is quite obvious because it's called "dbo.Bieren".

I can quite easily fix this by just renaming the table in the database. Altough i don't like fixing my database around my code's errors.

How can i make the entity framework use the correct table instead of changing the name of my table?

Thanks in advance.


回答1:


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



回答2:


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

[Table("Bieren")]



回答3:


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.



来源:https://stackoverflow.com/questions/6399443/entityframework-using-wrong-tablename

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