MVC - Checking existing user unique ID number (personal real number) in database [Answered]

- I need to create a new object (Person) and save it to the DB. That's done. - Now I want to include a unique ID number (it could be a Social Security Number, in the screenshot is NumberId) to every new person. Unique number is set as explained here: https://stackoverflow.com/a/22819292/7389293 which is a "Unique Key" - My problem: For every new person, I need to compare the incoming input with the existing Id numbers in the database. What's the best approach to get this done? Should I implement a method for this in some Controller, as a Service, as a Helper class somewhere, as a method belonging to the viewmodel.cs carrying that data from the view? What's best? I'm just looking for ideas on how to better approach this problem.
10 Replies
Angius
Angius3y ago
For every new person, I need to compare the incoming input with the existing Id numbers in the database
Why? You can let the insertion fail and handle the exception Other than that, do it in the service, yes Some sort of
var exists = await _ctx.Users.AnyAsync(u => u.Number == number);
if (exists) return Conflict();

_ctx.Users.Add(new User {
// ...
});
await _ctx.SaveChangesAsync();
var exists = await _ctx.Users.AnyAsync(u => u.Number == number);
if (exists) return Conflict();

_ctx.Users.Add(new User {
// ...
});
await _ctx.SaveChangesAsync();
As a side note, why is your class prefixed with an underscore..?
BlueJayBird
BlueJayBirdOP3y ago
I know it's bad practice. People in the project use it like that (_class). That specific class is used as a type for a list, which is displayed in a table. And never used in a form. I suppose that that's why use underscore.
Angius
Angius3y ago
Well fuck the people in the project
BlueJayBird
BlueJayBirdOP3y ago
I'll try to implement your solution. Can I implement this as a call from the front end? I feel the answer is yes.
Angius
Angius3y ago
I mean, how else will you create a new user? Unless you mean just the check? If so, then sure, just create the action in your user controller or w/e and you're good
BlueJayBird
BlueJayBirdOP3y ago
Yes, the check or validation over his/her ID number.
Angius
Angius3y ago
Just keep in mind to never trust the client. Whatever you check on the frontend, double-check on the backend
BlueJayBird
BlueJayBirdOP3y ago
What's w/e?
Angius
Angius3y ago
Whatever
Accord
Accord3y ago
✅ This post has been marked as answered!
Want results from more Discord servers?
Add your server