简体   繁体   English

查询表不在数据模型Edmx中

[英]Query Table not in Data Model Edmx

Normally if we want to execute a sql statment via entity frame work we would do the following. 通常,如果我们要通过实体框架工作执行sql语句,我们将执行以下操作。

DbSqlQuery<Customer> data = db.Customers.SqlQuery(
    "select * from customers where country=@p0", "USA");
foreach(var cust in data)
{
 //do something with cust
}

But thats ok for tables that are within the data model my question is how do i do a raw query against a table that is not already in the data model. 但这对于数据模型内的表是可以的,我的问题是如何对数据模型中尚未存在的表进行原始查询。 The reason being is that the software has what is called historic tables that is created the month and the year at the end of table so I cannot create these tables at runtime or would that be a better solution. 原因是该软件具有所谓的历史表,该表在表的末尾创建,因此我无法在运行时创建这些表,或者这将是一个更好的解决方案。

You can access the underlying connection and query these historical tables. 您可以访问基础连接并查询这些历史表。

var history = db.Database.SqlQuery<string>( "SELECT Name FROM dbo.historical_table").ToList(); 

Take a look at the following 看一下以下内容

EDIT -- If you wish to retuned multiple fields you have to capture the results into a class with matching property names, and (at least) a parameterless constructor 编辑-如果您希望重新调整多个字段,则必须将结果捕获到具有匹配属性名称的类中,并且(至少)应使用无参数构造函数

using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication10
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var db = new ConsoleApplication10.DBContext())
            {
                var list= db.Database.SqlQuery<DbResult>("SELECT display_name, country_code FROM dbo.mytable").ToList();
            }

        }
    }

    class DbResult
    {
        public string display_name { get; set; }
        public string country_code { get; set; }
    }
}

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

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