如何在实体框架通用插入方法中返回插入记录的ID?

编程入门 行业动态 更新时间:2024-10-27 10:32:15
本文介绍了如何在实体框架通用插入方法中返回插入记录的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(); } }

推荐答案

您需要做一些修改:

  • 您需要创建由实体实现的IHasAutoID

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

    本文发布于:2023-10-25 03:14:10,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1525756.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:实体   框架   方法   如何在   ID

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!