简体   繁体   English

C#实体框架字符串规范函数

[英]C# entity framework String Canonical Functions

How to use the Right function in entity framework query? 如何在实体框架查询中使用Right函数? I have this sql query 我有这个SQL查询

SELECT RIGHT('0' + '4'), DATEDIFF(MINUTE, DateReceived, GETDATE()) % 60), 2)  
FROM mytable //RESULTS = 04

The Right function will basically add 0 infront if the passed string's length is less than 2. 如果传递的字符串的长度小于2,则Right函数基本上将infront添加0

Now I want to do the same thing in entity framework query: 现在我想在实体框架查询中做同样的事情:

var query = (from b in sovDB.myTable
select new
{
    myMinutes = Right("0"+ (SqlFunctions.DateDiff("MINUTE", b.DateReceived,  
    SqlFunctions.GetDate()) % 60),2)
}).ToList();

But it doesnt work, somehow the Right function is not supported. 但是它不起作用,某种程度上不支持Right函数。

Just had the same issue when converting an old stored procedure to entity. 将旧的存储过程转换为实体时遇到了同样的问题。 I used SqlFunctions.Replicate which did the trick and Entity Framework had no complaints! 我使用了SqlFunctions.Replicate来达到目的,而Entity Framework没有任何抱怨!

var query = (from b in sovDB.myTable
select new
{
    myMinutes = SqlFunctions.Replicate("0", 2 - (SqlFunctions.DateDiff("MINUTE", b.DateReceived, GetDate()) % 60).Length) + (SqlFunctions.DateDiff("MINUTE", b.DateReceived, GetDate()) % 60)
}).ToList();

Try to explicitly convert calculated minute to string: 尝试将计算的分钟数显式转换为字符串:

var query = (from b in sovDB.myTable
select new
{
    myMinutes = Right("0" + SqlFunctions.StringConvert((int)(SqlFunctions.DateDiff("MINUTE", b.DateReceived, SqlFunctions.GetDate()) % 60)), 2)
}).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM