简体   繁体   中英

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.

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; }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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