dotnet / dotnet/efcore

Replacing Owned Entity with default value property is not propagated to database

Open
#27,509 3 comments 2 reactions 1 assignee Assigned to @AndriySvyryd View on GitHub
area-save-changes customer-reported
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

### What I am trying to do

With a model looking like the following, I am trying to set the `Value` to 0 for an `Item` stored in database.
`ItemValue` is defined as an owned entity of `Item`.
When I handle `ItemValue` as non mutable (by creating a new one for the update), no update is made in database and the previous value is kept in database.
When I handle the `ItemValue` as mutable and directly update it, the value is propagated to the database

```C#
public class Item
{
public string Key { get; set; }
public ItemValue ItemValue { get; set; }
}

public class ItemValue
{
public long Value { get; set; }
// the behaviors change when having a default date value, but still not an expected behavior
public DateTime Date { get; set; }// = DateTime.UtcNow;
}
```

```C#
public class ItemConfiguration : IEntityTypeConfiguration
{
public void Configure(EntityTypeBuilder entity)
{
entity.HasKey(e => e.Key);

entity
.ToTable("items");

entity
.OwnsOne(
e => e.ItemValue,
q =>
{
q
.Property(quotas => quotas.Value)
.HasColumnType("bigint(20)")
.HasDefaultValue(0);
q
.Property(quotas => quotas.Date)
.HasColumnType("datetime")
.HasDefaultValueSql("NOW()");
});
}
}
```
```C#
// non working update
using (var context = new SampleContext())
{
var item = context.Items.Find(key);
item.ItemValue = new ItemValue { Value = 0, };
context.SaveChanges();
}
```

A Sample project can be found here => https://github.com/robinroyer/ef-core-bug-report, generating a test for the update

```
➜ Sample git:(master) dotnet run
creating the value to : 666
====
setting the value to : 0
the value is now: 666 (1 values in db)
====
setting the value to : 1
the value is now: 1 (1 values in db)
====
setting the value to : 0
the value is now: 1 (1 values in db)
====
[WITHOUT CREATING A NEW OBJECT] setting the value to : 0
the value is now: 0 (1 values in db)
```

(the readme show a slightly different outcome when the owned entity have an other non default field)

Tested with MariaDB: `Server version: 5.5.5-10.6.4-MariaDB-1:10.6.4+maria~focal`

### What I was expecting

I was expecting the value to be updated in both cases :)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.