【发布时间】:2015-06-27 02:58:34
【问题描述】:
我的 Windows 窗体应用程序中有两个类。
假设Student 和StudentDetails 类StudentDetails 也是Student 类的属性。
我有一个从数据库中的两个表中获取数据的存储过程。 我需要知道这种情况通常是如何处理的,这意味着学生类通常是如何填充的。 非常感谢你的回答。 任何指向类似场景的链接都会很棒。
这是我的代码:
class Student
{
public int StudentID { get; set; }
public string StudentName { get; set; }
public StudentDetails StudentDetails { get; set; }
public Student()
{
this.StudentID = 0;
this.StudentName = String.Empty;
this.StudentDetails = new StudentDetails();
}
}
class StudentDetails
{
public int StudentDetailsID { get; set; }
public string Address { get; set; }
public int Height { get; set; }
public int Weight { get; set; }
public StudentDetails()
{
this.StudentDetailsID = 0;
this.Address = String.Empty;
this.Height = 0;
this.Weight = 0;
}
}
下面的类有一个填充学生类的函数(FillStudent())
Class StudentAssembler
{
public List<Model.Student> FillStudent()
{
List<Model.Student> StudentCollection = new List<Model.Student>();
Model.Student StudentDTO = new Model.Student();
try
{
using (Model.dbConnection dbconnection = new Model.dbConnection(Utilities.SqlConnStr))
{
SqlDataReader dr;
SqlCommand command = new SqlCommand("GetStudents", dbconnection.connection);
command.CommandType = CommandType.StoredProcedure;
dbconnection.OpenConn();
dr = command.ExecuteReader();
while (dr.Read())
{
StudentDTO.StudentID = dr[0] == DBNull.Value ? 0 : (int)dr[0];
StudentDTO.StudentName = dr[1] == DBNull.Value ? String.Empty : (String)dr[1];
//this is the part that i need to know how is it usually handled
//StudentDTO.StudentDetails = how to fill out this part ???
StudentCollection.Add(StudentDTO);
}
return StudentCollection;
}
}
catch (Exception)
{
return null;
}
}
}
编辑:
存储过程代码
select s.StudentID,s.StudentName,sd.StudentDetailsID,sd.Address,
sd.Height,sd.Weight
from Student s,StudentDetails sd
where s.StudentID = sd.StudentID
【问题讨论】:
-
这取决于“GetStudents”过程返回的内容。如果详细信息在那里,您可以简单地创建一个 StudentDetails 的新实例并设置属性。这不是处理这种事情的好方法吗?为什么不使用实体框架?
-
@Pseudonym:“代码损坏,请帮助”在 Code Review 中明确不在主题范围内。花点时间回顾一下那里可以提出什么样的问题:codereview.stackexchange.com/help/dont-ask
-
@Pseudonym 感谢您的评论,实际上我并没有使用发布的代码我只是把它作为一个例子我只需要帮助找到如何处理类似的场景什么是最佳实践或最佳设计模式:)
-
@Andrew 存储过程代码已发布,非常感谢
-
@nayefharb 似乎您的程序返回了您需要的一切。我发布了一个简单修复的答案。
标签: c# class oop design-patterns properties