Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customize DbContext properties names in Entity Framework and stop being overwritted?

EF auto-generate the DbContext class from my edmx file (database first) and use table names as default names for all this DbContext properties (ex: public DbSet<Student> student { get; set; })

If I make some change in this file (ex: like renaming properties name from student to Students), my changes are lost everytime I save my model because EF regenerate the DbContext class file.

How can I change this default behaviour and be able to make my customization and stop losing it?

like image 735
Etienne Desgagné Avatar asked Oct 14 '12 14:10

Etienne Desgagné


People also ask

How does DbContext change state of entity?

This can be achieved in several ways: setting the EntityState for the entity explicitly; using the DbContext. Update method (which is new in EF Core); using the DbContext. Attach method and then "walking the object graph" to set the state of individual properties within the graph explicitly.

How do I undo changes in Entity Framework?

To rollback changes we can use this behavior of the SaveChanges method. Just change the entity state from Modified to Unchanged, Added to Detached and reload the entity if its state is Deleted. This way is very useful when we need to rollback the changes of a specific entity or specific entities from DbContext.

Does DbContext need to be disposed?

Don't dispose DbContext objects. Although the DbContext implements IDisposable , you shouldn't manually dispose it, nor should you wrap it in a using statement. DbContext manages its own lifetime; when your data access request is completed, DbContext will automatically close the database connection for you.

Which method is used to let the DbContext know an entity should be deleted?

DbContext. Remove Method (Microsoft.


2 Answers

To elaborate on what Pawel said.. The EDMX file (the designer) is the source of everything. Any changes you need to make to the generated items should be done there. You can add additional methods or properties through partial classes, but you can't change existing ones.. so it must be changed in the source EDMX file.

Just right click on the Table in the designer, and rename it. This doesn't change the underlying table name (at least in Database First reverse engineering, model first is a different story).

like image 122
Erik Funkenbusch Avatar answered Oct 23 '22 03:10

Erik Funkenbusch


You need to change it in the Edmx file - you should be able to do that with the EF Designer

like image 28
Pawel Avatar answered Oct 23 '22 01:10

Pawel