Open PrgOrcl opened 3 days ago
Self contained repro:
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using var db = new MyContext();
db.Database.OpenConnection();
db.Database.EnsureCreated();
var data1 = new Author
{
Name = "aaa",
Contact = new ContactDetails
{
Address = new Address
{
City = "acity",
Country = "UK",
},
Phone = "01632 12345"
}
};
var data2 = new Author
{
Name = "bbb",
Contact = new ContactDetails
{
Address = new Address
{
City = "bcity",
Country = "Canada",
},
Phone = "01632 12346"
}
};
db.Author.Add(data1);
db.Author.Add(data2);
db.SaveChanges();
Console.WriteLine(db.Model.ToDebugString(Microsoft.EntityFrameworkCore.Infrastructure.MetadataDebugStringOptions.LongDefault));
var address = new Address
{
City = "acity",
Country = "UK",
};
var query = db.Author.Where(author => author.Contact.Address == address).ToList();
class MyContext : DbContext
{
public DbSet<Author> Author { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite();
optionsBuilder.LogTo(Console.WriteLine, events: [CoreEventId.QueryExecutionPlanned]);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Author>().OwnsOne(
author => author.Contact, ownedNavigationBuilder =>
{
ownedNavigationBuilder.ToJson();
ownedNavigationBuilder.OwnsOne(contactDetails => contactDetails.Address);
});
}
}
public class ContactDetails
{
public Address Address { get; set; } = null!;
public string? Phone { get; set; }
}
public class Address
{
public string City { get; set; }
public string? Country { get; set; }
}
public class Author
{
public int Id { get; set; }
public string Name { get; set; }
public ContactDetails Contact { get; set; }
}
Note for team: looks like it could be a dupe of ~#35147~ #29442. The issue is attempting to get the value of a shadow property from an object that isn't mapped. (Note that complex types don't have this issue.)
Yeah, I think the best answer here is to use complex types (when those are available)... As a workaround, it's possible to explicitly construct all the property comparisons in the LINQ query (the same SQL would be produced by EF in any case).
I have the following code below that queries a table with the following structure:
Here, "Contact" is a json column. We have mapped it to the Contact class in the OnModelCreation method.
In the linq in the given code, I'm trying to find the rows where the Address field in the Contact column is equal to the "address" I have defined locally. However, on running it I get the following exception :-
My question is - Is such a linq supported in efcore? If yes, then how do we write such a query? And is there any additional code or setup required for this?
EF Core version: 8 and 9 Database provider: (Microsoft.EntityFrameworkCore.SqlServer) Target framework: (NET 8.0) Operating system: Windows IDE: (Visual Studio 2022 17.4)