Get Id of Generic Entity of EF 6

c# entity-framework entity-framework-6 generics

Popular Answer

If you believe the element's ID to be along That is the first part of the key; you are explicitly assuming non-generic. Not every organisation has along key, if there even is one.

It's ideal to have this assumption explicitly expressed in the code if you have it. Make sure all entities inherit the basic entity class you create, which should have an ID. This will ensure that each object has a matching ID. If the column in your table has a different name, you may use the[Column] a characteristic 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.
}
1
9/25/2016 8:35:07 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow