c# - What should I be using here instead of ExecuteScalar? -


i'm trying return dbset<survey> survey defined as

public class survey {     public int id { get; set; }     [stringlength(100)]     public string title { get; set; } } 

the error i'm getting

an exception of type 'system.invalidcastexception' occurred in survey.dll not handled in user code  additional information: unable cast object of type 'system.int32' type 'system.data.entity.dbset`1[survey.models.survey]'. 

about dbset<survey> allsurveys = (dbset<survey>)cmd.executescalar(); line of

    public dbset<survey> getallsurveys ( )     {         sqlcommand cmd = new sqlcommand("getallsurveys", this._conn);         cmd.commandtype = commandtype.storedprocedure;         this._conn.open();         dbset<survey> allsurveys = (dbset<survey>)cmd.executescalar();         this._conn.close();         return allsurveys;     } 

the table in database , sproc i'm using generated by

create table surveys (     id int identity(1,1),     title nvarchar(100) not null,     primary key (id) ); go -- create sprocs adding, deleting, getting surveys create procedure addsurvey     @title nvarchar(100)     insert surveys (title) values (@title) go create procedure deletesurvey     @id int     delete surveys id=@id go -- seed surveys table 1 sample survey exec addsurvey @title = "survey numero uno";  go create procedure getallsurveys     select * surveys          order title asc; go 

any idea i'm going wrong?

this line dbset<survey> allsurveys = (dbset<survey>)cmd.executescalar(); return int. can try like:

edit based on comment old school .net. there 1 more thing in method can changed.

your full method this:

  public dbset<survey> getallsurveys ( )     {         using (sqlcommand cmd = new sqlcommand("getallsurveys", this._conn)         {            cmd.commandtype = commandtype.storedprocedure;            this._conn.open();            dbset<survey> allsurveys = new dbset<survey>();            using (sqldatareader datareader = cmd.executereader())                         {                             while (datareader.read())                             {                                 survey srv=new survey {                                   id = datareader.isdbnull(0)?default(int): datareader.getint32(0),                                   title =datareader.isdbnull(1)?string.empty: datareader.getstring(1)};                                 allsurveys.add(srv);                             }                         }            this._conn.close();            return allsurveys;     } } 

Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -