ASP.NET MVC获取最后添加的记录的ID [英] ASP.NET MVC Get ID of last added record

查看:195
本文介绍了ASP.NET MVC获取最后添加的记录的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MVC网络表单将记录插入到包含多个子记录的数据库中.在我的后台代码中,我首先使用dataRepository.Add(xx)创建一个新的主记录.现在,我需要添加5个需要新创建的记录的ID的子记录.我该如何找回呢?

I'm using an MVC webform to insert a record into a database with several subrecords. In my code-behind I'm first creating a new main record using dataRepository.Add(xx). Now I need to add 5 subrecords that need the ID of the newly created record. How can I retrieve that?

推荐答案

假设xx是您的模型,并且其主键是ID,则可以像这样获得插入记录的ID:

Assuming xx is your model, and its primary key is Id you can get the Id of your inserted record like this:

// at this point xx.Id == null
db.XX.AddObject(xx);
db.SaveChanges();
// now: xx.Id > 0
int id = xx.Id;

这篇关于ASP.NET MVC获取最后添加的记录的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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