Joe Ricklefs Joe Ricklefs - 4 months ago 44
C# Question

How to get ID of Entity When Using Generic Repository Pattern c#

Trying to figure out how to get the Id of the recently added entity when using Generic Repository pattern. An example would be nice.
here's the Repository,

public class Repository<T> : IRepository<T> where T : class {
protected DbContext DbContext { get; set; }
protected DbSet<T> DbSet { get; set; }
public Repository(DbContext dbContext)
if (dbContext == null)
throw new ArgumentNullException("dbContext");
DbContext = dbContext;
DbSet = DbContext.Set<T>();
public virtual void Add(T entity)
DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
if (dbEntityEntry.State == EntityState.Detached)
dbEntityEntry.State = EntityState.Added;

entity.Id doen'st exist here


If you step through your code, while running, you will see the ID (whatever you have it called) property will be populated after adding.

Your problem is, then, not with entity framework, but having a generic repository. You need a way to return the (assuming again) int ID you just added.

Create an interface:

public interface IEntity
    public int ID { get; set; }

and have all your models inherit from it. Then, change your type constraint to:

public class Repository<T> : IRepository<T> where T : IEnitity

then, you can return entity.ID after saving.