如何在实体框架通用插入方法中返回插入记录的ID? [英] How can I return the ID of the Inserted Record in Entity Framework Generic Insert Method?

查看:96
本文介绍了如何在实体框架通用插入方法中返回插入记录的ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是通用的插入方法。我需要您的建议以返回插入记录的ID。

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. 您需要创建由实体实现的IHasAutoID

  1. 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
        }
    }
    


  • 在您的Create函数中

  • 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:


    • 如果您确定所有表都具有名为 Id的自动ID。您无需创建接口IHasAutoID。在Create函数中,在SaveChanges之后,您可以使用REFLECTION获取Id属性的值,但是不建议这种方式!

    这篇关于如何在实体框架通用插入方法中返回插入记录的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆