我正在使用类DB上下文创建我的数据访问层他们有一些业务逻辑来获得最直接的学生如果一个不存在与recordID-1我创建一个新的。
public Student GetStudentById(int id)
{
try
{
Student studentRecord;
if (id == -1)
{
studentRecord = new Student();
schoolEntities.AddToStudents(studentRecord);
SaveChanges();
}
else
{
studentRecord = (from student in schoolEntities.Students
where student.Student_ID== id
select student).FirstOrDefault();
}
return studentRecord;
}
catch (Exception ex)
{
throw new EntityContextException("GetStudentById Failed", ex);
}
}
然后在我的网页上,我正在做以下
public partial class admin_students_edit : System.Web.UI.Page
{
public SISDBContext _db = new SISDBContext();
private Student _student;
protected void Page_Load(object sender, EventArgs e)
{
try
{
int id =Convert.ToInt32( Request.QueryString["id"]);
_student = _db.GetStudentById(id);
if(!IsPostBack)
{
txtStudentName.Text = _student.Student_Name;
txtStudentName.Text = _student.Student_FatherName;
txtRegistrationNo.Text = _student.Registration_no;
txtAddress1.Text = _student.Address1;
txtAddress2.Text = _student.Address2;
txtAddress3.Text=_student.Address3;
txtRelationshipGurdan.Text= _student.RelationWithGuadian;
txtGurdianName.Text= _student.GurdianName ;
txtLastSchool.Text = _student.LastSchoolAtten;
}
}
catch (Exception ex)
{
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
_student.Student_Name = txtStudentName.Text;
_student.Student_FatherName = txtStudentName.Text;
_student.Registration_no = txtRegistrationNo.Text;
_student.Address1 = txtAddress1.Text.Trim();
_student.Address2 = txtAddress2.Text.Trim();
_student.Address3 = txtAddress3.Text.Trim();
_student.RelationWithGuadian = txtRelationshipGurdan.Text.Trim();
_student.GurdianName = txtGurdianName.Text.Trim();
_student.LastSchoolAtten = txtLastSchool.Text.Trim();
_student.DOB = rdDOB.SelectedDate.Value;
_db.SaveChanges();
Response.Redirect("default.aspx");
}
catch (Exception ex)
{
}
}
由于某种原因,它保存了三次记录我不是没有原因因为我需要保存空白记录,如果一个不存在的话,想知道是否有人可以帮助我认为我的逻辑错过了某处。