更新与Postgres JSONB列映射的Entity Framework实体不会更新数据库。

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

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。为了更新数据库,我需要更新整个CustomersomeEntity.Customer = new Customer { Age = <new_value>, <set all other props to old values>}

英文:

Steps to reproduce:

  1. Create an EF Core project with SomeEntity entity as described on this page https://www.npgsql.org/efcore/mapping/json.html#poco-mapping in the POCO mapping section.

  2. Add code that creates a new instance of SomeEntity and calls SaveChanges() to persist it to the database.

  3. Add code that reads SomeEntity back (on a different instance of DbContext), updates it as follows someEntity.Customer.Age = <different_number_from_what_it_currently_is>, and calls SaveChanges().

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 🙂

huangapple
  • 本文由 发表于 2023年5月11日 13:10:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76224317.html
匿名

发表评论

匿名网友

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

确定