问题
Does anyone know how to change the mapped db table for an entity in EF4 (entity framework 4)?
Later edit: I think i've found the place where the table names are defined, in the model browser. But their names are readonly, so it's not possible to edit them using the designer. Also, there's no reference (from what i've searched) to the table name in the xml schema.
回答1:
If you just need to change the name of the table you can:
- Open EDMX file with XML Editor.
- Locate SSDL section in it.
- Locate entity set element for example
<EntitySet Name="Customers" EntityType="ExampleModel.Store.Customers" Schema="dbo" />. - Add
Table="MyTableName"attribute.<EntitySet Name="Customers" EntityType="ExampleModel.Store.Customers" Schema="dbo" Table="MyTableName" />
Here is a complete CSDL, SSDL, MSL specification.
Hope that helps.
回答2:
An alternative solution would be to override a method in your DbContext class.
public class MyDbContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>().ToTable("DB_PRODUCTS_TBL");
// otherwise EF assumes the table is called "Products"
}
}
回答3:
I believe what you are asking is reconfigure the mapping of an entity to a table. You can right click an entity and select table mapping. This would show you the entity the table is mapped. You can change the table in there. However when you open the dropdown, you will only see the table that you have imported using the Update Model wizard. If the table is not imported, it will not be listed. You can then map the properties appropriately to the column names of the table.
回答4:
In the Model Browser or design surface right-click the entity and select properties. In the properties window edit the field "Entity Set Name".
This worked for me, however I was designing the schema first and then generating the database.
回答5:
Because I created my database first, I did the following:
- Backed up the *.edmx file.
- Changed my database table name.
- Did as you suggested by renaming the Entity Set Name in the properties.
- I then Updated the model based on my database by right-clicking the entity.
- I noticed that the *.edmx file was missing half the lines, so I overlayed the *.edmx file with my backup, opened it in notepad, and did a replace all of my old table name with my new table name.
- Rebuilt the MVC Application, tested, and it worked.
Note: Whether all these steps above are needed I don't know, it's just what I tried and it worked for me.
回答6:
You can execute a stored proc that changes the table name, passing the tablename as a variable. Then import the stored proc into EF4.
CREATE PROCEDURE ChangeTableName
@TableName varchar(200)
AS
BEGIN
SET NOCOUNT ON;
EXEC sp_rename "User", @TableName
END
GO
来源:https://stackoverflow.com/questions/3276955/change-db-table-name-in-ef4-entity-framework-4