LINQ SqlQuery<T> with random number of fields selected

安稳与你 提交于 2019-12-13 05:33:30

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!