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

时间秒杀一切 提交于 2019-12-12 02:46:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!