title: FluentValidator extension method to check if entity exists in database
body: <p>I have a pretty common situation in which I need to validate when a reference property is being set in a given entity. When this happens I validate like this:</p>
  
  <pre class="lang-csharp prettyprint-override"><code>public class Validator : AbstractValidator&lt;Command&gt;
  {
      public Validator()
      {
          ...
  
          RuleFor(user =&gt; user.EmployeeId)
              .MustNotBeEmpty() 
              .MustAsync(ExistInDatabase).WithMessage("Employee not found"); 
      }
  
      public async Task&lt;bool&gt; ExistInDatabase(Command command, string id, CancellationToken cancelation)
      {
          return await _context.Employees.AnyAsync(x =&gt; x.Id == id.ToGuid());
      }
  }
  </code></pre>
  
  <p>This and other check in database are so much common and I'm writing methods like this in almost every validator.</p>
  
  <p>I would like to turn this into an extension method, in which I would pass the entity type, the context and the id. </p>
  
  <p>A <code>FluentValidation</code> extension method looks like this:</p>
  
  <pre class="lang-csharp prettyprint-override"><code>public static IRuleBuilderOptions&lt;T, string&gt; MustNotBeEmpty&lt;T&gt;(this IRuleBuilder&lt;T, string&gt; rule)
  {
      return rule
          .NotEmpty().WithMessage("O campo '{PropertyName}' não pode ser vazio");
  }
  </code></pre>
  
  <p>But these extension methods already receive generic types and I'm not figuring out how to pass another generic type to use with <code>context.Set&lt;T&gt;().AnyAsync(...)</code></p>
  
  <p>How could it be done?</p>
  
  <p>----- UPDATE -----</p>
  
  <p>I tried adding another generic type <code>T2</code> to the extension method but it does not work:</p>
  
  <pre class="lang-csharp prettyprint-override"><code>    public static IRuleBuilderOptions&lt;T, string&gt; MustExistInDatabase&lt;T, T2&gt;(this IRuleBuilder&lt;T, string&gt; rule, DatabaseContext context) where T2: BaseEntity
      {
          return rule.MustAsync(async (command, id, cancelation) =&gt; await context.Set&lt;T2&gt;().AnyAsync(x =&gt; x.Id == id.ToGuid())).WithMessage("'{PropertyName}' not found in database");
      } 
  </code></pre>
  
  <p>When I try to call it, the compiler complains that it could not found such extension method:</p>
  
  <pre class="lang-csharp prettyprint-override"><code>public class Validator : AbstractValidator&lt;Command&gt;
  {
      public Validator()
      {
          ...
  
          RuleFor(user =&gt; user.EmployeeId)
              .MustNotBeEmpty() 
              .MustExistInDatabase&lt;Employee&gt;(); 
      }
  }
  </code></pre>