我刚开始学习C#和.NET。我的问题可能很简单,但任何帮助都会很棒。
我的情景非常简单。我有两个三个表,学生,课程和入学,定义如下。
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace MyFirstProject.Models
{
public class Student
{
[Key]
public int StudentId { get; set; }
[Required(ErrorMessage = "Custom error message: First Name is required")]
[MaxLength(50)]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Custom error message: Last Name is required")]
[MaxLength(50)]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime EnrollmentDate { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace MyFirstProject.Models
{
public class Course
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int CourseId { get; set; }
public string CourseName { get; set; }
[Range(0, 5, ErrorMessage = "Number of credits must be between 0 and 5")]
public int TotalCredits { get; set; }
public ICollection<Enrollment> Enrollments { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace MyFirstProject.Models
{
public class Enrollment
{
public int EnrollmentId { get; set; }
public int StudentId { get; set; }
public int CourseId { get; set; }
[DisplayFormat(DataFormatString = "{0:#.#}", ApplyFormatInEditMode = true, NullDisplayText = "No Grade")]
public decimal? Grade { get; set; }
//Every enrollment has at least one student and one course.
public virtual Student student { get; set; }
public virtual Course course { get; set; }
}
}
现在,如果我想在一个数据库事务中将记录添加到Student表和Enrollment表中,我将如何进行此操作。 我们假设课程表中有三门课程: CourseId:1,CourseName:Math,TotalCredits:4 CourseId:2,CourseName:Physics,TotalCredits:4 CourseId:3,CourseName:Chemistry,TotalCredits:4
如果我尝试添加学生和注册,我将如何获得我正在添加的学生的ID? Psuedo代码如下:
Student s = new Student();
s.FirstName = "John";
s.LastName = "Doe";
db.Student.Add(s);
db.SaveChanges();
Enrollment e = new Enrollment();
e.CourseId = 1;
e.StudentId = s.StudentId //I need to get the student id for the above added student. How?
db.Enrollment.Add(e);
db.SaveChanges();
答案 0 :(得分:1)
不要手动设置ID。而是设置与student
属性的关系。
e.student = s;
对于它的价值,您还应该使用对象初始化,因为它使代码更清晰。而不是创建一个新实例,然后逐个填充属性,这样做:
var s = new Student
{
FirstName = "John",
LastName = "Doe"
};
var e = new Enrollment
{
CourseId = 1,
student = s
};
// this will actually add student as well since it's related
db.Enrollment.Add(e);
db.SaveChanges();
此外,如果您要添加新的相关项,则实际上可以组合两个对象初始化:
var e = new Enrollment
{
CourseId = 1,
student = new Student
{
FirstName = "John",
LastName = "Doe"
}
};