<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="11.0.0-preview.3.26207.106"> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets> </PackageReference> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="11.0.0-preview.3.26207.106" />
public class Customer { public int Id { get; set; } public required string Name { get; set; } public required Contact Contact { get; set; } } public class Contact { public required Address Address { get; set; } } public class Address { public required string Street { get; set; } public required string City { get; set; } public required string State { get; set; } public required string PostalCode { get; set; } } public class MyDbContext : DbContext { public DbSet<Customer> Customers { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder .UseSqlServer(@"<ConnectionString>", o => o.UseCompatibilityLevel(170)); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Customer>() .ComplexProperty(c => c.Contact, b => b.ToJson()); } }
EF.Functions.JsonPathExists()
// EF.Functions.JsonPathExists(): customers whose Contact JSON has an Address.PostalCode List<Customer> customersWithPostalCode = await context.Customers .Where(c => EF.Functions.JsonPathExists(c.Contact, "$.Address.PostalCode")) .ToListAsync();
SELECT [c].[Id], [c].[Name], [c].[Contact] FROM [Customers] AS [c] WHERE JSON_PATH_EXISTS([c].[Contact], N'$.Address.PostalCode') = 1
EF.Functions.JsonContains()
// EF.Functions.JsonContains(): customers in Redmond #pragma warning disable EF9106 // JsonContains is for evaluation purposes only List<Customer> redmondCustomers = await context.Customers .Where(c => EF.Functions.JsonContains(c.Contact, "Redmond", "$.Address.City") == 1) .ToListAsync(); #pragma warning restore EF9106
SELECT [c].[Id], [c].[Name], [c].[Contact] FROM [Customers] AS [c] WHERE JSON_CONTAINS([c].[Contact], N'Redmond', N'$.Address.City') = 1
Hope this helps.
Happy Coding.
Regards,
Jaliya
