简体   繁体   English

在没有 model 的原始查询中使用 EF7

[英]Using EF7 with raw queries without a model

I wonder if there is a way to use EF7 in fashion like Dapper without having a model generated from the database or otherwise generated.我想知道是否有一种方法可以像 Dapper 一样以时尚的方式使用 EF7,而无需从数据库生成或以其他方式生成 model。 Something like就像是

using(var context = new DbContext())
{
    string query = "...";
    var val = context.Database.ExecuteSqlCommand<RetVal>(query);
}

It looks like this is a well kept secret if there's a way.如果有办法的话,这看起来像是一个保守的秘密。 The idea here is to use EF7 as a thin wrapper over ADO.NET.这里的想法是使用 EF7 作为 ADO.NET 的精简包装器。

At this moment you cannot do that with EF core. 目前,您无法使用EF核心执行此操作

SQL queries can only be used to return entity types that are part of your model SQL查询只能用于返回属于模型的实体类型

You can see the limitations here : Raw SQL Queries Limitations 您可以在此处查看限制: 原始SQL查询限制

You can see the enhancement of it on EF Core backlog here : Support for ad hoc mapping of arbitrary types 您可以在EF Core待办事项列表上看到它的增强功能: 支持任意类型的临时映射

Actually, I think what you are looking for can be done (in EF7 as well as in older versions of EF).实际上,我认为您正在寻找的东西可以完成(在 EF7 以及旧版本的 EF 中)。 You will need to use the Command object to execute the query for you, and then parse the results from the Command Reader.您将需要使用命令 object 为您执行查询,然后从命令阅读器解析结果。

here is an example:这是一个例子:

using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using Microsoft.EntityFrameworkCore;

namespace IndexFragmentationExample
{
    public class IndexFragmentation
    {
        public string TableName { get; set; }
        public string IndexName { get; set; }
        public double FragmentationPercent { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (var db = new MyDbContext())
            {
                var indexFragmentations = GetIndexFragmentation(db);
                foreach (var indexFragmentation in indexFragmentations)
                {
                    Console.WriteLine("Table: " + indexFragmentation.TableName);
                    Console.WriteLine("Index: " + indexFragmentation.IndexName);
                    Console.WriteLine("Fragmentation: " + indexFragmentation.FragmentationPercent + "%");
                    Console.WriteLine();
                }
            }
        }

        private static List<IndexFragmentation> GetIndexFragmentation(DbContext db)
        {
            var fragmentations = new List<IndexFragmentation>();
            var connection = db.Database.GetDbConnection();
            connection.Open();
            using (var command = connection.CreateCommand())
            {
                command.CommandText = @"
                    SELECT 
                        OBJECT_NAME(ind.OBJECT_ID) AS TableName, 
                        ind.name AS IndexName, 
                        indexstats.avg_fragmentation_in_percent 
                    FROM 
                        sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, 'DETAILED') AS indexstats 
                    INNER JOIN 
                        sys.indexes AS ind 
                    ON 
                        ind.OBJECT_ID = indexstats.OBJECT_ID 
                        AND ind.index_id = indexstats.index_id";

                using (var reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        fragmentations.Add(new IndexFragmentation
                        {
                            TableName = reader["TableName"].ToString(),
                            IndexName = reader["IndexName"].ToString(),
                            FragmentationPercent = Convert.ToDouble(reader["avg_fragmentation_in_percent"])
                        });
                    }
                }
            }
            return fragmentations;
        }
    }

    public class MyDbContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=MyDb;Trusted_Connection=True;");
        }
    }
}

I hope this helps.我希望这有帮助。

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

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