1

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

Syed Mhamudul Hasan
  • 1,341
  • 2
  • 17
  • 45

2 Answers2

2

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.
}
Avner Shahar-Kashtan
  • 14,492
  • 3
  • 37
  • 63
0

After trying I find a temporary solution..but better answer is still not found ...

1 Mistake I made that not every entity (Table) contains id ..it is rather TableId

so my temporary solution is return the entity and get the value of identity column after added to db.

 //Create ///Get ID of the table
        public static T Add(CellPhoneProjectEntities dbContext, T entity, long id)
        {
            dbContext.Set<T>().Add(entity);
            dbContext.SaveChanges();
            return entity;
        } 

and to Get id

ServiceMaster master=some entity;;
long id=GenericRepo<ServiceMaster>Add(dbContext,master).ServiceMasterId;
Syed Mhamudul Hasan
  • 1,341
  • 2
  • 17
  • 45