如何为经典.NET在EF 6 Code First中使用SQL Server JSON_VALUE函数?我发现可以在 EF Core 中做到这一点,如下所示:
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();
但是,如何在经典.NET(以我的情况为4.6.1)中的EF 6中实现呢?
最佳答案
在经典的.NET中,它有点不同,但是仍然可以像这样:
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();
}
然后,由于在Entity Framework SQL Server提供程序 list 中未定义JSON_VALUE,因此您必须创建IStoreModelConvention,如下所示:
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();
}
}
关于c# - 如何在EF 6 Code First中将SQL Server JSON_VALUE函数用于经典.NET,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50490673/