Search code examples
c#jsonsql-serverentity-frameworkdbfunctions

How can I use SQL Server JSON_VALUE function in EF 6 Code First for classic .NET


How can I use SQL Server JSON_VALUE function in EF 6 Code First for classic .NET? I found I can do it in EF Core like this:

public static class JsonExtensions
{
    public static string JsonValue(string column, [NotParameterized] string path)
    {
        throw new NotSupportedException();
    }
}

// In OnModelCreating
modelBuilder.HasDbFunction(typeof(JsonExtensions).GetMethod(nameof(JsonExtensions.JsonValue)))
    .HasName("JSON_VALUE")
    .HasSchema("");

// And then the usage
var result = db.Blogs.Select(t => JsonExtensions.JsonValue(t.Log, "$.JsonPropertyName")).ToArray();

But how can I achieve this in EF 6 in classic .NET (in my case, its 4.6.1)?


Solution

  • In classic .NET it's a little bit different, but still possible like this:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Add(new RegisterJsonValueFunctionConvention());
    }
    
    // Than define your function
    [DbFunction("CodeFirstDatabaseSchema", "JSON_VALUE")]
    public static string JsonValue(string expression, string path)
    {
        throw new NotSupportedException();
    }
    

    Then, because JSON_VALUE is not defined in the Entity Framework SQL Server provider manifest, you have to create IStoreModelConvention like this:

    public class RegisterJsonValueFunctionConvention : IStoreModelConvention<EdmModel>
    {
        public void Apply(EdmModel item, DbModel model)
        {
            var expressionParameter = FunctionParameter.Create("expression", GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
            var pathParameter = FunctionParameter.Create("path", GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In);
            var returnValue = FunctionParameter.Create("result", GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.ReturnValue);
            CreateAndAddFunction(item, "JSON_VALUE", new[] { expressionParameter, pathParameter }, new[] { returnValue });
        }
    
        protected EdmFunction CreateAndAddFunction(EdmModel item, string name, IList<FunctionParameter> parameters, IList<FunctionParameter> returnValues)
        {
            var payload = new EdmFunctionPayload { StoreFunctionName = name, Parameters = parameters, ReturnParameters = returnValues, Schema =  GetDefaultSchema(item), IsBuiltIn = true };
            var function = EdmFunction.Create(name, GetDefaultNamespace(item), item.DataSpace, payload, null);
            item.AddItem(function);
            return function;
        }
    
        protected EdmType GetStorePrimitiveType(DbModel model, PrimitiveTypeKind typeKind)
        {
            return model.ProviderManifest.GetStoreType(TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(typeKind))).EdmType;
        }
    
        protected string GetDefaultNamespace(EdmModel layerModel)
        {
            return layerModel.GlobalItems.OfType<EdmType>().Select(t => t.NamespaceName).Distinct().Single();
        }
    
        protected string GetDefaultSchema(EdmModel layerModel)
        {
            return layerModel.Container.EntitySets.Select(s => s.Schema).Distinct().SingleOrDefault();
        }
    }