csharp EF6.x |将SQL与代码相关联

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp EF6.x |将SQL与代码相关联相关的知识,希望对你有一定的参考价值。

using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Infrastructure.Interception;
using System.Diagnostics;
using System.IO;
using System.Linq;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            GetMsdnBlogs();
            GetBlogs();
        }

        public static Blog[] GetMsdnBlogs()
        {
            using (var db = new BloggingContext())
            {
                return db.Blogs
                    .Where(b => b.Url.Contains("msdn"))
                    .OrderBy(b => b.Url)
                    .ToArray();
            }
        }

        public static Blog[] GetBlogs()
        {
            using (var db = new BloggingContext())
            {
                return db.Blogs
                    .SqlQuery("SELECT * FROM dbo.wrong_table")
                    .ToArray();
            }
        }
    }

    public class BloggingContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }
    }

    public class Blog
    {
        public int BlogId { get; set; }
        public string Url { get; set; }

        public List<Post> Posts { get; set; }
    }

    public class Post
    {
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }

        public int BlogId { get; set; }
        public Blog Blog { get; set; }
    }

    public class MyConfig : DbConfiguration
    {
        public MyConfig()
        {
            this.AddInterceptor(new PoorSqlLogger(@"C:\temp\log.txt", 1));
        }
    }

    public class PoorSqlLogger : DbCommandInterceptor
    {
        private readonly string _logFile;
        private readonly int _executionMillisecondThreshold;

        public PoorSqlLogger(string logFile, int executionMillisecondThreshold)
        {
            _logFile = logFile;
            _executionMillisecondThreshold = executionMillisecondThreshold;
        }

        public override void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
        {
            Executing(interceptionContext);
            base.ReaderExecuting(command, interceptionContext);
        }

        public override void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
        {
            Executed(command, interceptionContext);
            base.ReaderExecuted(command, interceptionContext);
        }

        public override void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
            Executing(interceptionContext);
            base.NonQueryExecuting(command, interceptionContext);
        }

        public override void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
        {
            Executed(command, interceptionContext);
            base.NonQueryExecuted(command, interceptionContext);
        }

        public override void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
            Executing(interceptionContext);
            base.ScalarExecuting(command, interceptionContext);
        }

        public override void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
        {
            Executed(command, interceptionContext);
            base.ScalarExecuted(command, interceptionContext);
        }

        private void Executing<T>(DbCommandInterceptionContext<T> interceptionContext)
        {
            var timer = new Stopwatch();
            interceptionContext.UserState = timer;
            timer.Start();
        }

        private void Executed<T>(DbCommand command, DbCommandInterceptionContext<T> interceptionContext)
        {
            var timer = (Stopwatch)interceptionContext.UserState;
            timer.Stop();

            if (interceptionContext.Exception != null)
            {
                File.AppendAllLines(
                    _logFile,
                    new string[]
                    {
                    "FAILED COMMAND",
                    interceptionContext.Exception.Message,
                    command.CommandText,
                    Environment.StackTrace,
                    string.Empty,
                    string.Empty,
                    });
            }
            else if (timer.ElapsedMilliseconds >= _executionMillisecondThreshold)
            {
                File.AppendAllLines(
                    _logFile,
                    new string[]
                    {
                    $"SLOW COMMAND ({timer.ElapsedMilliseconds}ms)",
                    command.CommandText,
                    Environment.StackTrace,
                    string.Empty,
                    string.Empty,
                    });
            }
        }
    }
}

以上是关于csharp EF6.x |将SQL与代码相关联的主要内容,如果未能解决你的问题,请参考以下文章

如何将 ResultSet 与 oracle 包规范中声明的游标相关联?

将属性与 .net 中的代码生成属性相关联

Rails 和 SQL - 与数组、条目中的所有元素相关联

SQL Server 维护计划如何与 Jobs 和 DTExec 相关联?

『 再看.NET7』泛性特性使用场景

将组合的索引与值相关联