title: C# Entity Framework, Get Inserted ID (Generic)
body: <p>I've got a method called AddFoo(Foo foo)</p>
  
  <pre><code>private int AddFoo(Foo foo)
  {
    Using (BarContext db = new BarContext())
    {
      db.Foos.Add(foo);
      db.SaveChanges();
    }
    return foo.FooID;
  }
  </code></pre>
  
  <p>I'd like to make it more generic to accept any entity and return an ID example (Rough and probably non functional just to show the idea:</p>
  
  <pre><code>private int Add(T entity)
  {
    Using (BarContect db = new BarContext())
    {
      // need to figure out how to find the appropriate set
      DbSet dbSet = //Set Appropriate dbset based on entity type
      dbSet.Add(entity);
      db.SaveChanges(); 
    }
    return entity.PrimaryKeyValue; // this would be the integer value of the id
  }
  </code></pre>
  
  <p>Now, I can use reflection to find an attribute marked with [Key] to figure out what property in the entity class holds the ID, but I don't think this is the most efficient. I can also hard code some map method that allows me to figure out what DBSet to add to... but I can't imagine that there isn't something out there that already does both these operations in a much more efficient way.</p>
  
  <p>So... How can I determine the Key and it's value and How can I figure out what DbSet to use in something this generic?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>Based on the answer below and the other similar post this is what I ended up doing... (pretty much just combined the two answers)</p>
  
  <pre><code>private static int GetEntityKeyValue&lt;T&gt;(this T entity) where T : class
  {
    int ret = 0;
    PropertyInfo key = typeof(T).GetProperties().FirstOrDefault(p =&gt; p.GetCustomAttributes(typeof(KeyAttribute), true).Length != 0);
    if (key != null)
    {
      ret = (int)key.GetValue(entity, null);
    }
    return ret;
  }
  
  private static int Add&lt;T&gt;(T entity) where T : class
  {
    using (Foo db = new FooContext())
    {
      DbSet dbset = db.Set&lt;T&gt;();
      dbset.Add(entity);
      db.SaveChanges();
    }
    return entity.GetEntityKeyValue();
  }
  </code></pre>
  
  <p>I wanted to stay away from reflection... but, meh. Looks like that's the way.</p>
  
  <p>Thanks all.</p>