我们发现最简单的方法是修补入站的Linq2Sql代码。 我们还注意到,DbFunctions.AddMinutes()仅接受Int32,而DateTime.AddMinutes()接受double。这可能会破坏预期的行为,因此我们也进行了修补。使用一些正则表达式和一些简单的字符串操作,得到了这个已打补丁的代码。
这可能不适用于所有人,但如果您正在从Linq2Sql转换并且有遵循Linq2Sql的保存查询,并且需要修补DateTime表达式...这将适用于AddMintues、AddDays、AddHours、AddMilliseconds。
private static string Linq2SqlConvertToEntityFramework(string originalQuery)
{
const string dateTimeAdditationPattern = @"(@?[a-z_A-Z]\w*(?:\.@?[a-z_A-Z]\w*)*).Add\s*.+?(?=\))\)";
var matchces = Regex.Matches(originalQuery, dateTimeAdditationPattern);
foreach (Match m in matchces)
{
var inputValue = m.Value;
string valuePassed = inputValue.Between("(", ")").Trim();
string typeOfAddition = inputValue.Between(".Add", "(").Trim();
string dateTimeExpression = inputValue.Before(".Add").Trim();
var mutipler = 1;
switch (typeOfAddition)
{
case "Seconds":
mutipler = 1000;
break;
case "Minutes":
mutipler = 1000*60;
break;
case "Hours":
mutipler = 1000 * 60 * 60;
break;
case "Days":
mutipler = 1000 * 60 * 60 * 24;
break;
}
var replacementString = string.Format("DbFunctions.AddMilliseconds({0},(int)({1} * {2}))", dateTimeExpression, valuePassed, mutipler);
originalQuery = originalQuery.Replace(inputValue, replacementString);
}
return originalQuery;
}
public static string Between(this string value, string a, string b)
{
int posA = value.IndexOf(a, StringComparison.InvariantCulture);
int posB = value.LastIndexOf(b, StringComparison.InvariantCulture);
if (posA == -1)
{
return "";
}
if (posB == -1)
{
return "";
}
int adjustedPosA = posA + a.Length;
if (adjustedPosA >= posB)
{
return "";
}
return value.Substring(adjustedPosA, posB - adjustedPosA);
}
public static string Before(this string value, string a)
{
int posA = value.IndexOf(a, StringComparison.InvariantCulture);
if (posA == -1)
{
return "";
}
return value.Substring(0, posA);
}
public static string After(this string value, string a)
{
int posA = value.LastIndexOf(a, StringComparison.InvariantCulture);
if (posA == -1)
{
return "";
}
int adjustedPosA = posA + a.Length;
if (adjustedPosA >= value.Length)
{
return "";
}
return value.Substring(adjustedPosA);
}