How to reflect the changing of my entities names t

2019-09-05 15:22发布

问题:

I have set of Entities generated according to DB First work flow in EntityFramework.

The Entities have in proper names so i decide to change them but when i change the Entity name, the navigation property keeps the pluralization and the singularization of the old name like the following : Two Entities (SREmp ,SRPic)

SREmp      SRPic

Id         id
name       content
phone      note
- - -      - - -
SRPics     SREmp

Now when i change the names of my entities to (Employee,EmpPhoto), the navigation properties didn't change !!

回答1:

As you know, when you use the DB First approach, you're using a T4 template that extracts the information from the database to create the model entities. So, the model entities will get their names and properties from the information in the databse.

So, if you need to customize the names of your properties, there are only two ways to do it, and both involve customizing the T4 template:

  1. if you cannot modify your database in any way, because you don't want to do it or you don't have permissions, modify the T4 template by including a dictionary that maps the database table names to the desired entity names. Then, along the T4 template code, use the dictionary to create the entity names, and also the navigation property names.

  2. if you can modify the databse, modify it by adding information about the desired entity names, navigation names and so on. You can do it in extended properties, or using naming conventions for, for example, the foreign key constraints.

The 2nd solution can be implemented in several different ways. For example, I use the FK constraint names to define the navigation properties. I name my DB FKs soemthing like FK_Employee_Pictures, so that the template create the navigation properties Employee in the pictures table, and Pictures in the employee table. This is really powerful, because you can't give precise names to your relations, with names like FK_Empoyee_FacePicture or Fk_Employee_IdCardPicture. You can also use extended properties, like the descriptions, to access them from your T4 template. You can define your own conventions, and then you have to modify the T4 template to use them.

Any other possible solution requires manual intervention, which is a very bad idea. You could find all uses of a given entity in your model project, and make a rename refactor. But that's expensive, and, if you modify your database, you'll need to update you model entities by hand again. Using any of the previous solutions you only have to update the mapping dictionary, or the DB conventions, and run the T4 template again, which is much cheaper and repeatable.

You should look for a powerfu, and easy to understand an customize template. I really like this one: EntityFramework Reverse POCO Generator.