I write a generic repository to CRUD in EF.In add method is written like this
public class GenericRepo<T> where T : class
{
//Create
public static void Add(CellPhoneProjectEntities dbContext, T entity)
{
dbContext.Set<T>().Add(entity);
dbContext.SaveChanges();
}
}
works fine by i want to get first element of the Entity(Primary key ,Identity column )
public static long Add(CellPhoneProjectEntities dbContext, T entity,long id)
{
dbContext.Set<T>().Add(entity);
dbContext.SaveChanges();
var pk = entity.ElementType.KeyMembers[0];
//Something like first elemnt by generic
return pk as Long;
}
can anyone help to get First element(Id) of entity after insertion?
EDIT: EF database first and my primary key is not named Id..
Rather it is TableNameId eg. Table ProjectMaster has primary key ProjectMasterId
When you assume that the element's ID is a long
that's the first element of they key, you're making explicitly non-generic assumptions. Not all entities have a long
key, or a key at all.
If you have this assumption, it's best to have it explicitly stated in the code. Create a base entity class with an ID, and ensure all entities inherit it. That way you know each entity has a compatible ID. If your table's column is named differently, you can use the [Column]
attribute to map between them:
public abstract class EntityBase
{
public virtual long Id {get; set;}
}
public class MyEntity : EntityBase
{
[Column("TableId"]
public override long Id {get;set;}
}
public long Add(DbContext context, T entity) where T : EntityBase
{
var storedEntity = dbContext.Set<T>().Add(entity);
dbContext.SaveChanges();
return storedEntity.Id; // Will always have the property.
}