我应该在这里使用什么而不是ExecuteScalar?

时间:2016-01-28 14:25:33

标签: c# sql asp.net asp.net-mvc tsql

我试图返回DbSet<Survey> Survey定义为

public class Survey
{
    public int Id { get; set; }
    [StringLength(100)]
    public string Title { get; set; }
}

我得到的错误是

An exception of type 'System.InvalidCastException' occurred in Survey.dll but was not handled in user code

Additional information: Unable to cast object of type 'System.Int32' to type 'System.Data.Entity.DbSet`1[Survey.Models.Survey]'.

关于<{p>}的DbSet<Survey> AllSurveys = (DbSet<Survey>)cmd.ExecuteScalar();

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

数据库中的表和我使用的sproc是由

生成的
CREATE TABLE Surveys (
    id INT IDENTITY(1,1),
    title NVARCHAR(100) NOT NULL,
    PRIMARY KEY (id)
);
GO
-- Create sprocs for adding, deleting, getting surveys
CREATE PROCEDURE AddSurvey
    @title NVARCHAR(100)
AS
    INSERT INTO Surveys (title) VALUES (@title)
GO
CREATE PROCEDURE DeleteSurvey
    @id INT
AS
    DELETE FROM Surveys WHERE id=@id
GO
-- Seed the surveys table with 1 sample survey
EXEC AddSurvey @title = "Survey Numero Uno";

GO
CREATE PROCEDURE GetAllSurveys
AS
    SELECT * FROM SURVEYS 
        ORDER BY title ASC;
GO

知道我哪里出错了吗?

1 个答案:

答案 0 :(得分:5)

这一行DbSet<Survey> AllSurveys = (DbSet<Survey>)cmd.ExecuteScalar();将返回一个int。您可以尝试以下方式:

编辑根据您对旧学校.NET的评论。你的方法还有一件事可以改变。

您的完整方法可能如下所示:

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