如何找到在实体框架的最后插入的行的身份? [英] How to find an identity of the last inserted row in Entity Framework?

查看:106
本文介绍了如何找到在实体框架的最后插入的行的身份?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在多个表中插入数据。我需要知道最后插入(自动递增)表中的ID。我需要使用它作为在其他一些表一个Foriegn密钥

I am inserting data in multiple tables. I need to know the last inserted (auto-incremented) ID in the table. I need to use it as a Foriegn Key in some other table.

总之我需要的替代@@身份在T-SQL。

In short I need alternative of @@Identity in T-Sql.

推荐答案

实体框架会自动加载最后插入的ID来填充插入实体的主键列:

Entity Framework will automatically load the last inserted id to populate the primary key column of the inserted entity:

var customer = new Customer() { Name = "Steven" };

context.AddObject(customer);

context.SaveChanges();

var id = customer.Id;

注意编号属性只被填充调用的SaveChanges()的情况下, StoreGeneratedPattern 属性被设置为标识,或计算在模型的存储部的自增ID列

Note that the Id property only gets populated after calling SaveChanges() in case the StoreGeneratedPattern attribute is set to "Identity" or "Computed" for the auto-incremented ID column in the Storage part of the model.

这篇关于如何找到在实体框架的最后插入的行的身份?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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