- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个表格,其中小数(和其他类型)保存为字符串。我想在数据库上下文中编写一个 Linq 查询,它将转换为数据库转换而不是本地转换(出于性能原因)。
这个非工作示例在概念上是我想要实现的。
using ( var context = new MyContext() )
{
return context.SomeTable
.Select(o => new { o.Id, (decimal)o.SomeString });
}
这是实现它的坏方法,因为它将在应用程序端运行转换。
using ( var context = new MyContext() )
{
return context.SomeTable
.Select(o => new { o.Id, o.SomeString })
.ToList()
.Select(o => new { o.Id, Convert.ToDecimal(o.SomeString) });
}
我相信要走的路是使用 DbFunctions,但我找不到将它与 Code First 一起使用的方法。
这是部分答案,但我无法找到完成我定义此函数在 SQL 服务器上的作用的部分所需的文档。
[DbFunction("MyContext", "ConvertToDecimal")]
public static decimal ConvertToDecimal(string s)
{
throw new Exception("Direct calls are not supported.");
}
.
using ( var context = new MyContext() )
{
return context.SomeTable
.Select(o => new { o.Id, ConvertToDecimal(o.SomeString) });
}
如果我使用的是 Edmx 驱动的替代方案,这将是缺失的部分:
<Function Name="ConvertToDecimal" ReturnType="Edm.Decimal">
<Parameter Name="s" Type="Edm.String" />
<DefiningExpression>
CAST(s AS decimal(22,6))
</DefiningExpression>
</Function>
我正在使用 Entity Framework 6 Code First。
最佳答案
我根据来自 this 的一些信息找到了解决方案主题。
就像我在最初的问题中假设的那样,我已经记下了前两部分。最后一部分是在 DbModel 中注册您想要访问的功能以及如何使用它们。有不止一种方法可以做到这一点,但我使用了一个约定
public class MyFunctionsConvetion : IStoreModelConvention<EntityContainer>
{
public void Apply(EntityContainer item, DbModel model)
{
//Get the Edm Model from the DbModel
EdmModel storeModel = model.GetStoreModel();
//Delare your parameters name, edm type and mode (You can ignore this if you use a parameter-less function)
List<FunctionParameter> Parameters = new List<FunctionParameter>();
Parameters.Add(FunctionParameter.Create("StringValue", GetStorePrimitiveType(model, PrimitiveTypeKind.String), ParameterMode.In));
//Same thing goes for the return type(s) (Why is it a list? Perhaps you can return tables? I haven't tested however since it is no use to me)
List<FunctionParameter> ReturnParameters = new List<FunctionParameter>();
ReturnParameters.Add(FunctionParameter.Create("ReturnValue", GetStorePrimitiveType(model, PrimitiveTypeKind.Decimal), ParameterMode.ReturnValue));
//Create the payload and fill the required information alone with the parameter lists we declared
EdmFunctionPayload payload = new EdmFunctionPayload();
payload.IsComposable = true;
payload.Schema = "dbo";
payload.StoreFunctionName = "ConvertToDecimal";
payload.ReturnParameters = ReturnParameters;
payload.Parameters = Parameters;
//Create the function with it's payload
EdmFunction function = EdmFunction.Create("ConvertToDecimal", "MyContext", DataSpace.SSpace, payload, new MetadataProperty[] { });
//Add it to the model
storeModel.AddItem(function);
}
//Little helper method to get the primitive type based on the database provider
private EdmType GetStorePrimitiveType(DbModel model, PrimitiveTypeKind typeKind)
{
return model
.ProviderManifest
.GetStoreType(TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(typeKind)))
.EdmType;
}
}
然后我们在OnModelCreating方法中给模型添加Convention
modelBuilder.Conventions.Add<MyProject.MyConventions.MyFunctionsConvention>();
注意:代码可以更简洁并以 DRY 方式编写,但为了简单起见,我想像这样发布它并让您按照自己认为合适的方式组织它。
关于c# - 如何使用自定义 DbFunction 将字符串转换为小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22352312/
我有以下代码,它会截断时间: // does this already exist? var seekScan = (from s in aDb.Item_Scan_Event
我有一个表格,其中小数(和其他类型)保存为字符串。我想在数据库上下文中编写一个 Linq 查询,它将转换为数据库转换而不是本地转换(出于性能原因)。 这个非工作示例在概念上是我想要实现的。 using
我想从数据库中获取一个列表,其中 MyDate 是今天或明天。 我写了下面的代码。 _Log("Now: " + DateTime.Now.ToString()); var v = db_TS.TS_
我尝试通过遵循 this ticket 中最流行的答案来模拟 DbFunctions.Like 函数并像这样创建它的本地实现: public static class DbFunctions {
我有这个 LINQ 到实体: var result = (from inspArch in inspectionArchives from inspAuth in insp
我试图仅按日期过滤数据(截断时间)。数据库中的字段是DateTime。 作为引用,我尝试了这个解决方案,但不起作用: 'Date' is not supported in LINQ to Entiti
我有 100 行不同日期的数据。我想每隔 30 分钟按相同日期对结果进行分组。 相反: 结果一,2016-02-02 13:00:24 结果一,2016-02-02 13:01:24 结果一,2016
我不确定这是否可行,因为我刚刚深入研究 Entity Framework 6。我们正在从 Linq2Sql 迁移,但我们的引擎中有许多基于用户的查询。我们根据用户需求动态编译一些代码,并且必须保持向后
我有一项任务是在特定时间段内获取一组实体。我正在使用代码优先方法和 MySql 服务器。 代码 IQueryable query = dbContext.Set().AsNoTracking(); E
var vals = (from r in result group r by DbFunctions.TruncateTime(r.Created) into
我正在寻找类似 EF.Functions.FreeText 的内容这是在 SQL Server 中实现的,但使用了 MATCH...AGAINST MySQL的语法。 这是我目前的工作流程: AspN
我目前正在尝试对通过 Entity Framework 运行的查询运行一些单元测试。查询本身在实时版本上运行没有任何问题,但单元测试总是失败。 我已将此范围缩小到我对 DbFunctions.Trun
有什么区别: EntityFunctions.TruncateTime 和 DbFunctions.TruncateTime methods? 最佳答案 没有区别。 EntityFunctions 是
我目前正在尝试对通过 Entity Framework 运行的查询运行一些单元测试。查询本身在实时版本上运行没有任何问题,但单元测试总是失败。 我已将此范围缩小到我对 DbFunctions.Trun
我正在尝试在 LinqPad 中使用以下内容(C# 语句): DbFunctions.TruncateTime(mvOutDt).ToString() 它似乎无法识别 DbFunctions。我添加了
我的 .net 应用程序中有以下正常运行的 LINQ public ActionResult Index() { Dictionary> result;
我有一个带有外键链表的模型,即 [Table("a"] public class A { [Key] [Column("a_id")] public int Id { get;
在哪里results1是一个 IQuerable在您尝试按日期过滤之前效果很好: results1 = results1.Where(l => DbFunctions.DiffDays(FromDat
我有一个使用 C# 编写的应用程序在 ASP.NET MVC 5 框架之上。此外,我使用 EntityFramework 6.2 作为 ORM 来与我的数据进行交互。 我使用 Fluent LINQ
我之前有以下设置: public static bool BlogIsLive(BlogPost b) { return b.Status == (int)ItemStatus.Active
我是一名优秀的程序员,十分优秀!