EF Core Add函数返回负ID [英] EF Core Add function returns negative id

查看:431
本文介绍了EF Core Add函数返回负ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,当我尝试保存实体并在EF Core中返回其ID时,我注意到了一件奇怪的事情

I noticed a weird thing today when I tried to save an entity and return its id in EF Core

之前:

之后:

Before: After:

我在考虑是否在调用saveChanges()之前,但是它可以与具有类似设置的另一个实体一起使用。

I was thinking about if it was before calling saveChanges() but it works with another entity with a similar setup.

ps:我使用工作单元进行保存

ps: I use unit of work to save all changes at the end.

原因是什么?

推荐答案

在您保存更改之前,它将为负。只需在上下文中调用 Save

It will be negative until you save your changes. Just call Save on the context.

_dbContext.Locations.Add(location);
_dbContext.Save();

保存后,您将拥有数据库中的ID。您可以使用事务,如果获得ID后出现问题,可以回滚。

After the save, you will have the ID which is in the database. You can use transactions, which you can roll back in case there's a problem after you get the ID.

另一种方法是不使用数据库的内置IDENTITY领域,而是自己实施。当您执行大量批量插入操作时,此功能非常有用,但是它要付出一定的代价,因此难以实现。

The other way would be not to use the database's built-in IDENTITY fields, but rather implement them yourself. This can be very useful when you have a lot of bulk insert operations, but it comes with a price — it's not easy to implement.

这篇关于EF Core Add函数返回负ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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