问题
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
回答1:
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.
来源:https://stackoverflow.com/questions/39861045/how-to-get-id-of-entity-when-using-generic-repository-pattern-c-sharp