问题
I am making a run time sql query and getting data from database using LINQ SqlQuery<>
SchoolSoulLibrary.SchoolSoulDataEntities ss = new SchoolSoulLibrary.SchoolSoulDataEntities();
string query1;
var li = ss.Database.SqlQuery<MasterBank>(query1).ToList();
where MasterBank class is
public Partial class MasterBank
{
public MasterBank()
{
}
public decimal BankId { get; set; }
public string BankName { get; set; }
public Nullable<decimal> UserId { get; set; }
public Nullable<decimal> SchoolId { get; set; }
}
if i am executing this query
query1 = "Select * from MasterBank"; or
query1 = "Select BankId,BankName,UserId ,SchoolId from MasterBank";
Its not giving any error and returning all data
but if i am executing this query
query1 = "Select BankName,SchoolId from MasterBank";
error occured
i understand the reason of this error that it return a result of the type of class MasterBank but what can i do now because query1 is generating runtime with random no of properties of class MasterBank.
is there any other alternative of doing it rather than SqlQuery<>
kindly suggest
回答1:
All the fields that are optional need to be marked as optional (nullable) in MasterBank class.
This one shouldn't cause any problems:
query1 = "Select BankId ,SchoolId from MasterBank";
So the quickest fix is just to make all your fields nullable.
回答2:
EDIT
My original answer was way off...
I think you will need the type you use to match the result you expect. So define a new type to match your query:
class SomeClass
{
public string BankName {get;set;}
public int SchoolId {get;set;}
}
SchoolSoulLibrary.SchoolSoulDataEntities ss = new SchoolSoulLibrary.SchoolSoulDataEntities();
string query1;
var li = ss.Database.SqlQuery<SomeClass>(query1).ToList();
If you don't know until runtime what fields you will return - consider using a dataset instead of entity framework or try something like this:
http://www.codeproject.com/Articles/206416/Use-dynamic-type-in-Entity-Framework-4-1-SqlQuery
来源:https://stackoverflow.com/questions/19952912/linq-sqlqueryt-with-random-number-of-fields-selected