英文:
Updating Entity Framework entity mapped to Postgres JSONB column does not update the database
问题
创建一个EF Core项目,并按照此页面https://www.npgsql.org/efcore/mapping/json.html#poco-mapping中“POCO映射”部分的描述创建SomeEntity实体。
添加代码,创建SomeEntity的新实例,并调用SaveChanges()将其持久化到数据库。
添加代码,在不同的DbContext实例上读取SomeEntity,并按照以下方式更新它:someEntity.Customer.Age = <different_number_from_what_it_currently_is>,然后调用SaveChanges()。
预期的结果是数据库中将更新客户年龄,但实际上没有任何变化。查看ChangeTracker中的实体,我发现SomeEntity被跟踪为Unchanged。为了更新数据库,我需要更新整个Customer:someEntity.Customer = new Customer { Age = <new_value>, <set all other props to old values>}。
英文:
Steps to reproduce:
-
Create an
EF Coreproject withSomeEntityentity as described on this page https://www.npgsql.org/efcore/mapping/json.html#poco-mapping in thePOCO mappingsection. -
Add code that creates a new instance of
SomeEntityand callsSaveChanges()to persist it to the database. -
Add code that reads
SomeEntityback (on a different instance of DbContext), updates it as followssomeEntity.Customer.Age = <different_number_from_what_it_currently_is>, and callsSaveChanges().
The expected outcome is that customer age will be updated in the DB, but actually no change happens. Looking at the entities in the ChangeTracker, I can see that SomeEntity is being tracked as Unchanged. To get the DB updated, I need to do update the whole Customer: someEntity.Customer = new Customer { Age = <new_value>, <set all other props to old values>}.
答案1
得分: 1
你可以尝试将 DBContext 的 IsModified 属性设置为要更新的 JSON 列,然后调用 SaveChanges()。
这是一个示例:
_dbContext.Entry(SomeEntity).Property(x => x.Customer).IsModified = true;
试试看如何 🙂
英文:
You can try setting the IsModified property from the DBContext to the JSON column you wish to update, and then calling SaveChanges()
Here's an example:
_dbContext.Entry(SomeEntity).Property(x => x.Customer).IsModified = true;
Let me know how it goes 🙂
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论