Reload of Entity won't refresh value of owned type
Entities and DbContext
public class MyDbContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder
.UseSqlServer("Server=localhost;Database=EFCore_Sample_OwendTypesReloading;Integrated Security=true;TrustServerCertificate=True");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Book>(b =>
{
b.ToTable("Books");
b.OwnsOne(v => v.Price,
zr =>
{
zr.Property(dr => dr.Amount).HasColumnName("Amount");
zr.Property(dr => dr.CurrencyCode).HasColumnName("CurrencyCode");
});
});
}
public DbSet<Book> Books { get; set; }
}
public class Book
{
public int Id { get; set; }
public string? Title { get; set; }
private Money? _price;
public Money? Price
{
get => _price;
set => _price = value?.Clone();
}
}
public class Money : ICloneable
{
public Money()
{
Amount = 0m;
CurrencyCode = null;
}
public Money(decimal amount, CurrencyISOCode? currencyCode = null)
{
Amount = amount;
CurrencyCode = currencyCode;
}
public decimal Amount { get; }
public CurrencyISOCode? CurrencyCode { get; }
public Money Clone()
{
var clone = (Money)MemberwiseClone();
return clone;
}
object ICloneable.Clone() => Clone();
}
public enum CurrencyISOCode
{
EUR = 978,
USD = 840,
GBP = 826,
}
Example
await using (MyDbContext dbContext = new MyDbContext())
{
await dbContext.Database.EnsureDeletedAsync();
await dbContext.Database.EnsureCreatedAsync();
}
await using MyDbContext dbContext1 = new MyDbContext();
Book book1 = new() { Title = "My Book" };
dbContext1.Add(book1);
dbContext1.SaveChanges();
await using MyDbContext dbContext2 = new MyDbContext();
Book book2 = dbContext2.Books.First();
book1.Price = new Money(10);
dbContext1.SaveChanges();
dbContext2.Entry(book2).Reload();
if (book2.Price?.Amount != book1.Price?.Amount)
throw new InvalidOperationException($"The Price of the reloaded Book is '{book2.Price?.Amount.ToString() ?? "NULL"}' but should be '{book1.Price?.Amount.ToString() ?? "NULL"}'"); ⛔
We're using EFCore 7.0.1 in our Desktop Application where lifetime of the DbContext is as long as one view is alive. When some values in the database changes, we use the dbContext.Entry(entity).Reload() to reload some entities. But owned type values are not refreshed if the previous local value was NULL - see example code.
We recently upgraded from EFCore 2.2.6 to EFCore 7.0.1 In EFCore 2.2.6 everything was refreshed correctly.
Include provider and version information
EF Core version: 7.0.1 Database provider: Microsoft.EntityFrameworkCore.SqlServer Target framework: .NET 7.0 Operating system: Windows 11 IDE: Visual Studio 2022 17.4.3
@thumer The behavior here is currently as designed; Reload only reloads the root entity--#13890 and #1985 are tracking improvements in this area. For now, Reload must also be called on the owned entity. For example:
dbContext2.Entry(book2).Reload();
dbContext2.Entry(book2.Price).Reload();
I'm not 100% sure why this was behaving differently in 2.2. It is likely at least partially due to Dependent entities sharing the table with the principal are now optional. Certainly, doing this:
Book book1 = new() { Title = "My Book" };
dbContext1.Add(book1);
dbContext1.SaveChanges();
results in no Price being saved to the database. Instead, this is needed:
Book book1 = new() { Title = "My Book", Price = new Money()};
dbContext1.Add(book1);
dbContext1.SaveChanges();
But either way, Reload should not have been reloading the owned entity.
The problem is, that in case if the book has no price - so if book2.Price == null, I can't reload it, because there is no EntityEntry. And it would be a different behavior if a Book has a "empty price" new Money() (-> Value would be 0) compared to a book with no price null.
At 2.2 we had used an empty Money Object, with an Amount = null. But with 7.0 there must be at least one not-nullable property in an owned type, which is a good rule when the OwnedType-Value itself can be null.
@thumer That's what the breaking change referenced above is about. If the book has an empty price, then when it is loaded the Prince navigation is null, just as it was when the book was saved.
Of course, but in this case the reloading dbContext2.Entry(book2.Price).Reload() is impossible 🤔
@thumer Yes. Something that doesn't exist cannot be loaded and hence cannot be reloaded.
In summary:
If the price of the book is subsequently set or changed in the database, then you can only query this value by handle multiple cases and load/reload this entity with OwnedType-Value or by removing the book entity from the ChangeTracker and then querying the book again.
Refresh-Examples with 2 OwnedType-Values Price and Price2
if (book2.Price == null || book2.Price2 == null)
book2 = dbContext2.Books.First();
if (book2.Price != null)
dbContext2.Entry(book2.Price).Reload();
if (book2.Price2 != null)
dbContext2.Entry(book2.Price2).Reload();
dbContext2.Entry(book2).Reload();
--> Multiple SQL Statments
or
dbContext2.Entry(book2).State = EntityState.Detached;
book2 = dbContext2.Books.First();
--> 1 SQL Statement, but difficult to use if I have a graph of entities in dbcontext
Yes, this is working as expected.
@ajcvickers Owned types are included by default when the owner is queried. I think reload shouldn't differ from this behavior and I hope this will be corrected in future.