N
N
Nikolai2020-03-02 14:50:12
WPF
Nikolai, 2020-03-02 14:50:12

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();


I would like to be able to validate something like this:

if (_emp.IsValid())
{
    _context.Employees.Add(_emp);
    _context.SaveChanges();
}


But I don't know which is better. If you edit the Employees code, then the edits will be erased if you need to regenerate the EF tables. I also thought about doing it through extension methods, but somehow I don’t really want to add static classes, because they will constantly hang in memory. You can create separate classes for validation and pass _emp to the validation method as an argument. But maybe there is some way to still do the validation in the employee class itself and so that it is not overwritten?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikolay, 2020-03-05
@pinkertem

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.

P
Peter, 2020-03-02
@petermzg

You have a false belief that "static classes are somehow not particularly desirable, because they will constantly hang in memory."
If your class with Extensions does not contain static class members, then nothing will be in memory.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question