实体框架6&在生成SQL

时间:2017-11-21 11:47:00

标签: entity-framework entity-framework-6

我们正在为您的项目使用其他项目DLL。对于参考项目DLL,在实体框架6中生成SQL期间,SQL Server保留关键字为小写。

我们尝试了很多方法,之后我们只使用IDbCommandInterceptor获得了一个解决方案,如下所示:

public class CustomEFInterceptor : IDbCommandInterceptor
{
    public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
    {
        AppendToLog(command);
    }

    private void AppendToLog(DbCommand command)
    {
        string sqlStr = new StringBuilder(command.CommandText).Replace("INSERT", "insert").Replace("VALUES", "values")
                                                  .Replace("UPDATE", "update").Replace("SET", "set")
                                                  .Replace("DELETE", "delete")
                                                  .Replace("WHERE", "where")
                                                  .Replace("\r\n", " ").ToString();
        //// ..... Added to DB Table and Executed during some other process.
    }
}

是否有使用EF6 Model Builder约定或配置的其他解决方案?

public partial class TestEntities : DbContext
{
    public TestEntities() : base("name=TestEntities3")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}

提前致谢。

1 个答案:

答案 0 :(得分:2)

您也可以不区分大小写地查找索引,而不是处理sql关键字。

string sql = "SELECT * FROM SomeTable WHERE Column1 LIKE '%reyan%'";
int index = sql.IndexOf("where", StringComparison.OrdinalIgnoreCase); // index = 24

您甚至可以为此创建扩展方法。

public static class StringExtensions
{
    public static bool Contains(this string statement, string word, StringComparison stringComparison)
    {
        return statement?.IndexOf(word, stringComparison) >= 0;
    }
}


string sql = "SELECT * FROM SomeTable WHERE Column1 LIKE '%reyan%'";
bool contains = sql.Contains("where", StringComparison.OrdinalIgnoreCase); // contains = true

但是再次如David所建议的,如果您的任何单词与sql关键字匹配,那么您也将获得该单词的索引。