新加入的实体ID的SaveChanges()之前 [英] Id of newly added Entity before SaveChanges()

查看:224
本文介绍了新加入的实体ID的SaveChanges()之前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我添加一个实体到我的数据库,像这样:

 公共TEntity添加(TEntity实体)
{
回报(TEntity)已_database.Set< TEntity方式>()添加(实体);
}



但是, DbSet.Add 方法不返回与ID等新加入的实体,它只是回来时,我传递给我的添加方法。

$ b对象
$ b

应该是路过我回去包括编号,完整的新的实体或者是不可能得到的标识的SaveChanges()被称为?


解决方案

所有调用添加()是在做与数据上下文有效注册它,这样的实体进行跟踪。没有实际操作是反对这个时间,直到数据库中完成(如你正确地提)你叫的SaveChanges()



我假设你正在使用您的表自动生成的ID;在这种情况下,它的数据库引擎,这将产生记录时插入的ID和实体框架会读这回并填充实体适合你。



所以,确认您的怀疑,没有 - 这是不可能的前的SaveChanges得到ID()被称为在这种情况下



<。 p>希望这有助于!


I am adding an entity to my database like so:

public TEntity Add(TEntity entity)
{
     return (TEntity)_database.Set<TEntity>().Add(entity);
}

However, the DbSet.Add method isn't returning the newly added entity with the Id etc, it is simply returning the object I passed in to my Add method.

Should it be passing me back the complete new entity including Id, or is it not possible to get the Id before SaveChanges() is called?

解决方案

All the call to Add() is doing is effectively registering it with the data context so that the entity can be tracked. No actual operation is done against the database at this time until (as you rightly mention) you call SaveChanges().

I'm assuming that you're using automatically-generated Ids in your table; in this case, it's the database engine which will generate that Id when the record is inserted, and Entity Framework will read this back and populate your entity for you.

So, to confirm your suspicions, no - it's not possible to get the Id before SaveChanges() is called in this case.

Hope this helps!

这篇关于新加入的实体ID的SaveChanges()之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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