Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/Infinite-Square/efcoreextensions
support for OPENJSON sql server syntax with linq to entities through EFCore
https://github.com/Infinite-Square/efcoreextensions
Last synced: about 2 months ago
JSON representation
support for OPENJSON sql server syntax with linq to entities through EFCore
- Host: GitHub
- URL: https://github.com/Infinite-Square/efcoreextensions
- Owner: Infinite-Square
- License: mit
- Created: 2018-06-19T13:27:34.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2022-12-08T03:45:37.000Z (about 2 years ago)
- Last Synced: 2024-04-18T08:06:27.995Z (9 months ago)
- Language: C#
- Size: 132 KB
- Stars: 15
- Watchers: 4
- Forks: 1
- Open Issues: 6
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# efcoreextensions
support for OPENJSON sql server syntax with linq to entities through EFCore# Context
- Your project use EF Core (2.1.1).
- You need some JSON features of SQL Server (```JSON_VALUE```, ```JSON_QUERY```, ```OPENJSON```).
- You don't want to use FromSql
You can use this extension library with a new extension method ```ValueFromOpenJson```.# Configuration
You have to declare some fake ```DbSet``` (due to actual limitation of EFCore) :
```csharp
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity>();
modelBuilder.Entity>();
modelBuilder.Entity>();
}
```
You can use SQLServer or InMemory provider :
```csharp
optionsBuilder.UseExtensions(extensions =>
{
//extensions.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=testdbapp2;Trusted_Connection=True;");
extensions.UseInMemoryDatabase("inmemory");
});
```# Usages
If you want to EF Core generate valid SQL with right usage of ```OPENJSON```, you have to use the method ```ValueFromOpenJson``` on a fake DbSet of ```JsonResult```. You have to declare this DbSet as a variable :
```csharp
var json = appContext.Set>();
```
Next you can query a real DbSet (mapped to an existing table) :
```csharp
var query = appContext.Persons
.Where(p => json.ValueFromOpenJson(p.Kinds, "$").Select(jr => jr.Value).Contains("kind2"));
```
The variable query is a classic ```IQueryable```, you trigger the SQL Command with ```ToList``` or ```ToListAsync``` from EFCore :
```csharp
var result = await query.ToListAsync();
```
The SQL generated :
```SQL
SELECT [p].[Id], [p].[Kinds], [p].[Name]
FROM [Persons] AS [p]
WHERE N'kind2' IN (
SELECT [jr].[Value]
FROM (
SELECT [Key], [Value], [Type] FROM OPENJSON([p].[Kinds], N'$')
) AS [jr]
)
```# TODOs
- [ ] declare JsonResult DbSet automaticaly
- [ ] SQLite support