DbContext没有从数据库中提供任何数据

时间:2017-12-09 18:08:56

标签: entity-framework

我有两组代码。第一个没有给我数据列表,但第二个没有。请参阅以下代码:

第一个代码: 的模型

public class Student
{
    [Key]
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public string Gender { get; set; }
}

DataConnection

public class DataConnection : DbContext
{
    public DataConnection()
        : base("DefaultConnection")
    {

    }
    public DbSet<Student> Students { get; set; }
}

接口

public interface IStudent
{
    List<Student> StudentList();
    void InsertStudent(Student student);
    void UpdateStudent(Student student);
    Student GetStudentById(int id);
    void DeleteStudent(int id);
}

混凝土

readonly DataConnection _context;

public StudentConcrete()
{
    _context = new DataConnection();
}

public List<Student> StudentList()
{
    var studentList = (from s in _context.Students select s).ToList();
    return studentList;
}

第二代码 混凝土

readonly DataConnection _context;

public StudentConcrete()
{
_context = new DataConnection();
}

public List<Student> StudentList()
{
    SqlConnection xxx = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
    var cmd = new SqlCommand("GetAllStudents", xxx);
    var da = new SqlDataAdapter(cmd);
    var ds = new DataSet();
    da.Fill(ds);
    if (ds.Tables[0].Rows.Count > 0)
    {
        return (from DataRow row in ds.Tables[0].Rows
                select new Student()
                {
                    Age = Convert.ToInt32(row["Age"]),
                    FirstName = row["FirstName"].ToString(),
                    Gender = row["Gender"].ToString(),
                    LastName = row["LastName"].ToString()
                }).ToList();
    }
    else
    {
        return null;
    }

}

我想使用第一个代码获取数据,但我不知道哪里弄错了。我的SP只是为了吸引学生。

1 个答案:

答案 0 :(得分:1)

我怀疑你可能会以某种方式从另一张桌子中检索记录。您是否尝试为Student实体添加Table属性。

using System.ComponentModel.DataAnnotations.Schema;

[Table("Students")]
public class Student
{
    [Key]
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public string Gender { get; set; }
}