-1

I'm using FluentValidation library to create validators like this:

Please any one help me to simplify this part of code?

private bool UniqueSimNo(string simNo)
    {
        MyContext _db = new MyContext();
        Sim s = _db.Sims.Where(x => x.SimNo.ToLower() == simNo.ToLower()).SingleOrDefault();
        var sim = _db.Sims.Where(x => x.SimNo.ToLower() == s.SimNo.ToLower()).Where(x => x.Id != s.Id).FirstOrDefault();
        if (sim == null) return true;
        return false;
    }
Zinov
  • 3,817
  • 5
  • 36
  • 70

1 Answers1

0

Well, your code doesn't make sense if you don't pass an id as parameter to your method.

I guess you wanna use the same validator for a new item (id = 0) and an existing (id !=0).

This line doesn't do what you think it is doing after your SingleOrDefault test, as SingleOrDefault would raise an exception if there was more than one item with same SimNo : var sim = _db.Sims.Where(x => x.SimNo.ToLower() == s.SimNo.ToLower()).Where(x => x.Id != s.Id).FirstOrDefault();

So I would do

private bool UniqueSimNo(string simNo, int id = 0) {
    var _db = new MYContext());
    return !_db.Sims.Any(x => x.Id != id && x.simNo.ToLower() == simNo.ToLower()); 

}
Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122