title: How to write an extension method in DbContext class?
body: <p>I want to create a helper method to check an item exists or not in datatabase.</p>
  
  <p>I've tried this:</p>
  
  <pre><code>public static class DbContextExtensions
  {
      public static bool Exist&lt;TModel&gt;(this DbSet&lt;TModel&gt; model, string id) where TModel : class
      {
          return !string.IsNullOrEmpty(id) &amp;&amp; model.SingleOrDefault(x =&gt; x.Id == id) != null;
      }
  }
  </code></pre>
  
  <p>I'm getting this error message:</p>
  
  <blockquote>
    <p>'TModel' does not contain a definition for 'Id' and no extension method 'Id' accepting a first argument of type 'TModel' could be found (are you missing a using directive or an assembly reference?)</p>
  </blockquote>
  
  <p>What I want to achieve:</p>
  
  <pre><code>public class PostManager
  {
      private readonly _dbContext;
  
      public PostManager(MyDbContext dbContext)
      {
          _dbContext = dbContext;
      }
  
      public async Task&lt;IdentityResult&gt; UpdateAsync(EditPostViewModel model)
      {
          if (_dbContext.Users.Exist(model?.UserId) &amp;&amp; _dbContext.Posts.Exist(model?.Id))
          {
              // the user with "UserId" and the post with "Id" are existing...
          }
      }
  }
  </code></pre>
  
  <p>I don't want to create a helper method inside the <code>PostManager</code> class, like this:</p>
  
  <pre><code>public class PostManager
  {
      // contructor...
  
      // actions...
  
      private bool UserExist(string id)
      {
          return !string.IsNullOrEmpty(id) &amp;&amp; _dbContext.Users.SingleOrDefault(x =&gt; x.Id == id) != null;
      }
  
      private bool PostExist(string id)
      {
          return !string.IsNullOrEmpty(id) &amp;&amp; _dbContext.Posts.SingleOrDefault(x =&gt; x.Id == id) != null;
      }
  }
  </code></pre>
  
  <p>Because the method <code>UserExist</code> and <code>PostExist</code> may be used in many another classes. So, I don't want to re-declare them in every class before using.</p>
  
  <p>How can I do that? Thank you so much!</p>