简体   繁体   中英

How to correctly use EF5's DbContext to get values using a SQL query?

I've been trying to wrap my head around the correct way to use EF5's DbContext to query data using SQL. I am fully aware that EF is an ORM and would normally be used with linqTOentities and entity objects. But I have an interesting case requiring SQL.

Here's the sample code that I've been using:

testQuery = "select 'HITHERE' as firstval, 'HOTHERE' as secondval;";
var results = DataContext.Database.SqlQuery<string>(testQuery);

When I run the code above (C#) I get the following error:

{"The data reader has more than one field. Multiple fields are not valid for EDM primitive or enumeration types."}

I figured that the error had to do with the string part of .SqlQuery<string>(testQuery) not being the correct type to bind to. So I changed the code to this:

testQuery = "select 'HITHERE' as firstval, 'HOTHERE' as secondval;";
var results = DataContext.Database.SqlQuery<List<string>>(testQuery);

When I run this updated code, results has no values, count is 0. However, when I run the test sql query in SSMS I get what you would expect; one row, two values with columns names. firstVal = HITHERE and secondVal = HOTHERE.

How can I bind those select values to variables in C# with DbContext?

DataContext.Database.SqlQuery<string>(testQuery); is expected a single string value per row so the following query would satisfy this setup

select 'HITHERE' as firstval
union
select 'HOTHERE' as secondval;";

for the query you are running you would need a class (or some type) with 2 string properties

public class resultsClass
{
    public string firstval { get; set; }
    public string secondval { get; set; }
}

and you can then do

var results = DataContext.Database.SqlQuery<resultsClass>(testQuery);

which should contain one result


UPDATE

Your example seems to contain key/value pairs - are you able to use this?

select 'firstValue', 'HITHERE'
union
select 'secondValue', 'HOTHERE'

public class resultsClass
{
    public string key { get; set; }
    public string value { get; set; }
}

var results = DataContext.Database.SqlQuery<resultsClass>(testQuery);

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