Answer the question
In order to leave comments, you need to log in
What is the best way to implement validation of a class generated by the Entity Framework?
There is a MS SQL DB and a WPF project. Entity Framework Core is used to work with this database. He generated classes for each table, in this question we will be interested in the class Employee - Employees. When creating a new employee, before saving, you need to check whether all fields are filled in correctly.
The MVVM pattern is used and when creating a ViewModel, which is a visual page for creating an employee, a new instance of the Employees class (_emp) and an instance of the context (_context) are passed to it, in order to just save to the database. Through binding, all page fields are associated with this _emp and saving is done like this:
_context.Employees.Add(_emp);
_context.SaveChanges();
if (_emp.IsValid())
{
_context.Employees.Add(_emp);
_context.SaveChanges();
}
Answer the question
In order to leave comments, you need to log in
The most convenient way to do this is through the partial class.
All classes generated by EF are already partial, i.e. you can create another class with the same name, also declare it partial and add the required functionality to it. After compilation, the partial classes will merge into one. Important: partial classes must be in the same namespace.
In my case, EF classes are in the Model/Entities folder. I created a Model/EntitiesExt folder and created a partial class Employees in it. At the same time, I manually renamed the namespace Model.EntitiesExt to Model.Entities. Thus, both classes ended up in the same namespace, although in different folders. I added the IsValid method to my Employees and, in fact, that's it. If I suddenly regenerate EF classes, then my class will remain untouched.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question