问题
Here is the generic insert method. I need your suggestion to return the ID of the inserted record.
public static void Create<T>(T entity) where T : class
{
    using (var context = new InformasoftEntities())
    {
        DbSet dbSet = context.Set<T>();
        dbSet.Add(entity);
        context.SaveChanges();
    }
}
    回答1:
You need a little modification:
You need to create an IHasAutoID that implemented by Entity
public interface IHasAutoID { int getAutoId(); }In Entity Class
public class EntityA : IHasAutoID { public int getAutoId() { return pk; // Return -1 If the entity has NO Auto ID } }In your Create function
public static int Create<T>(T entity) where T : class { using (var context = new InformasoftEntities()) { DbSet dbSet = context.Set<T>(); dbSet.Add(entity); context.SaveChanges(); if (entity is IHasAutoID) { return ((IHasAutoID)entity).getAutoId(); } return -1; // entity is NOT IHasAutoID) } }NOTES:
- If you are sure all tables have Auto ID with named "Id". You don't need to create Interface IHasAutoID. In Create function, after SaveChanges, You use REFLECTION to get value of Id property, but this way is not recommended!
 
回答2:
Arturo Martinex is correct in his comment.
Entity framework fixes up the ID's during SaveChanges so it's already updated in the entity you passed in to the method.
To do specifically what you ask you could change your generic constraint from class to a new abstract class that all your entities inherit, which defines the key in that class.
   public static int Create<T>(T entity) where T : BaseEntity
    {
        using (var context = new InformasoftEntities())
        {
            DbSet dbSet = context.Set<T>();
            dbSet.Add(entity);
            context.SaveChanges();
            return entity.Id;
        }
    }
public abstract class BaseEntity
{
   int Id { get; set;}
}
This technique is more useful in an InsertOrUpdate method
Another way to work with keys inside generic methods is to interrogate the MetaData as described here:
The key to AddOrUpdate
回答3:
public async Task<int> Add(TEntity entity)
{
 await _context.Set<TEntity>().AddAsync(entity);
 await Save();
 return Task.FromResult(entity).Id;
}
    来源:https://stackoverflow.com/questions/20427347/how-can-i-return-the-id-of-the-inserted-record-in-entity-framework-generic-inser