0
votes

If I have multiple dbSets within my dbContext, for example:

  • public DbSet Persons { get; set; }
  • public DbSet Companies { get; set; }
  • public DbSet<...>

How could I than create a generic function to check if the value of a dynamically passed field already occurs?

Function in pseudo code:

bool IsFieldValueUnique<T>(field, fieldValue)
{
  return DbSet<T>.Any(x => x.field == fieldValue)
}

And function calls could then be something like:

var result1 = IsFieldValueUnique<Person>(Person.Email, somePersonObject.Email)

var result2 = IsFieldValueUnique<Company>(Company.Identification, someCompanyObject.Identification)

When searching around, I find approaches like using '<Func<T, bool>>', but can't connect the dots together.

2

2 Answers

1
votes

Func<T, bool> - Sounds like the right approach to what you want.

bool IsFieldValueUnique<T>(Func<T, bool> checkFunction)
{
  var alreadyExists = DbSet<T>.Any(checkFunction);
  return !alreadyExists;
  //Other ways to do this, but this is just for clarity.
}

Then you call it like:

IsFieldValueUnique<Person>(person => person.Email == somePersonObject.Email)

What you have now is a method IsFieldValueUnique that takes a check function. This check function takes in a T (of the same type as you use in the DbSet) and returns a boolean value.

person => person.Email == somePersonObject.Email is an anonymous function that for a given instance of a Person compare the Email property with somePersonObject.Email.

If you look at the signature for Any you will see similarities with the checkFunction signature.

If you want to try it on Customer you can:

IsFieldValueUnique<Customer>(cust => person.Name == someCustomer.Name);

Note:

Calling Any like this: DbSet<T>.Any(checkFunction);

Is the same as this: DbSet<T>.Any(item => checkFunction(item));

0
votes
bool IsFieldValueUnique<T>(Expression<Func<T, bool>> predicate)
{
  return DbSet<T>.AsQueryable().Any(predicate.Compile());
}

And use it like this:

bool unique = IsFieldValueUnique<Person>(p => p.Email == something.Email);