开发者

EntityFramework using wrong tablename

My code is giving me an EntityCommandExecutionException when i'm trying getting data from my Bieren开发者_如何学C 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.


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

[Table("Bieren")]


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜