How can I return the ID of the Inserted Record in Entity Framework Generic Insert Method?

与世无争的帅哥 提交于 2020-08-27 12:45:12

问题


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:

  1. You need to create an IHasAutoID that implemented by Entity

    public interface IHasAutoID {
        int getAutoId();
    }
    
  2. In Entity Class

    public class EntityA : IHasAutoID {
    
        public int getAutoId() {
            return pk; // Return -1 If the entity has NO Auto ID
        }
    }
    
  3. 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)
        }
    }
    
  4. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!