获取Entity Framework中使用PostgreSQL添加的最后一个记录的ID。

huangapple go评论70阅读模式
英文:

Get last added record id in entity framework with postgreSQL

问题

Students表格具有id、name、gender和address列。id是标识列。当使用以下代码将每个学生的详细信息添加到该表中:

_dataContext.Students.Add(student);
_dataContext.SaveChanges();

我需要获取最后插入的id值。我需要将这个id值插入到另一个表中,比如'Subject'表中的studentid列。

如何获取最后插入的id值?

英文:

Students table has id ,name , gender,address columns. id is the identity column. when each student details added to this table using below lines of code,

 _dataContext.Students.Add(student);
_dataContext.SaveChanges();

I need to get last inserted id value. this id value I need to insert to other table say 'Subject' table as studentid column.

How can I get last inserted id ?

答案1

得分: 3

SaveChanges 方法已经拿到了 IdSaveChanges 方法负责检索所有持久化对象的ID并修复它们之间的关系。

当调用 SaveChanges 方法时,DbContext 检测到跟踪的对象的所有修改,并在单个事务中持久化所有这些修改。SaveChanges 本质上是一个 Commit() 调用,应该只在工作单元/业务交易的最后调用。

SaveChanges 会保存所有新的或修改过的对象的更改,检索新对象的新ID并修复关系。之后,student.Id 应该具有新的值,以及与其相关的任何其他新类。

这意味着你可以编写以下代码来持久化新的课程和学生,并获取它们的ID。

var course = new Course(...);
foreach (var i = 0; i < 10; i++)
{
    course.Students.Add(new Student(...));
}

context.Courses.Add(course);

context.SaveChanges();

Console.WriteLine($"Course ID: {course.Id}");
foreach (var s in course.Students)
{
    Console.WriteLine($"Student ID: {s.Id}");
}

DbSet.Add 方法将根课程和所有可达的对象都添加到 DbContext 中,并将它们标记为 Added 状态。所有这些都将被 SaveChanges 保存。

如果你想放弃更改,只需不调用 SaveChanges。当 DbContext 被处理后,更改也将丢失。

这就解释了为什么所有非“repository” CRUD 类都会出现问题。像这样的方法:

public int BadInsert(Student student)
{
    _context.Students.Add(student);
    _context.SaveChanges();
}

无法回滚可能执行的多个DELETE、UPDATE和INSERT操作,除了单个的 Student。如果出现问题,你必须显式打开连接并启动一个长时间运行的事务,才能回滚该学生。

英文:

You already the Id. SaveChanges takes care of retrieving the IDs and fixing up relations for all the objects it persists.

A DbContext detects all modifications to the objects it tracks and persists all of them in a single transaction when SaveChanges is called. SaveChanges is essentially a Commit() call and should only be called at the very end of a unit of work/business transaction.

SaveChanges will save all changes for all new or modified objects, retrieve the new IDs for the new objects and fix up relations. After it, student.Id should have the new value, along with any other new class related to it.

This means you could write the following code to persist a new course and students, and get back the IDs for all of them.

var course=new Course(...);
foreach(var i=0;i&lt;10;i++)
{
    course.Students.Add(new Student(...));
}

context.Courses.Add(course);

context.SaveChanges();

Console.WriteLine($&quot;Course ID: {course.Id}&quot;);
foreach(var s in course.Students)
{
    Console.WriteLine($&quot;Student ID: {s.Id}&quot;);    
}

The DbSet.Add method add both the root course and all reachable objects to the DbContext in the Added state. All of these will be saved by SaveChanges.

If you want to discard the changes, just don't call SaveChanges. When the DbContext gets disposed, the changes will be lost too.

That explains why all the non-"repository" CRUD classes are so badly broken. A method like this :

public int BadInsert(Student student)
{
    _context.Students.Add(student);
    _context.SaveChanges();
}

Has no way of rolling back the possibly dozens of DELETEs, UPDATE and INSERTs it may execute beyond the single Student. You'd have to explicitly open a connection and start a long-running transaction to be able to roll back that Student if something goes wrong.

答案2

得分: -2

SELECT timestamp, value, card
FROM my_table
ORDER BY timestamp DESC
LIMIT 1

英文:

SELECT timestamp, value, card
FROM my_table
ORDER BY timestamp DESC
LIMIT 1

huangapple
  • 本文由 发表于 2023年2月24日 16:45:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75554357.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定