I’m working on a reusable database repository method for attaching and saving entities to a database using EntityFramework 4.3.
private void SaveObject<T>(T entityToSave, DbSet<T> dbSet) where T : class
{
if (db.Entry(entityToSave).State == EntityState.Detached)
{
if (entityToSave.Id == Guid.Empty) // how do I access the Id property?
dbSet.Add(entityToSave);
else
db.Entry(entityToSave).State = EntityState.Modified;
}
}
The problem that I’m running into is that I need to tell my method which property is the Id so I can check to see if it is set or not. If it is empty, then I know I am creating a brand new record. Otherwise I am modifying an existing record.
How do I tell my method what the Id property is?
You need an interface or base class that defines the
Idproperty, and use that as your generic constraint. Example: