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.
- Open the EDMX file in Visual Studio
- Delete the incorrect "Biers" table
- right-click in the background and click "Update Model from database"
- Point the wizard at your database, and select the "Bieren" table to add
- 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.
精彩评论