Joe Ricklefs
Joe Ricklefs

Reputation: 660

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)
        {
            DbSet.Attach(entity);
            dbEntityEntry.State = EntityState.Added;
        }
        else
        {
            DbSet.Add(entity);
        }
   }
}

entity.Id doen'st exist here

Upvotes: 0

Views: 2697

Answers (1)

Jonesopolis
Jonesopolis

Reputation: 25370

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.

Upvotes: 1

Related Questions