我有一个Student
课程和一个Standard
课程。例如:
public class Student
{
public Student() { }
public int StudentId { get; set; }
[Required]
public string StudentName { get; set; }
public int StdandardId { get; set; }
public virtual Standard Standard { get; set; }
}
public class Standard
{
public Standard()
{
StudentsList = new List<Student>();
}
public int StandardId { get; set; }
public string StandardName { get; set; }
public string Description { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
现在我正在存储这样的记录:
我的数据库中已有一些标准条目。假设我有一个id为4的标准条目。现在我正在存储与该
对应的学生Student s=new student();
s.StudentName="Priyesh";
s.StandardId=4;
context.Student.add(s);
context.savechanges();
现在我想将学生对象返回到具有标准对象集的UI,但我将标准对象作为null(s.Standard
为null)。请提出解决方案。
答案 0 :(得分:0)
您需要使用Id 4检索标准对象,并将学生添加到其学生集合中,并将标准对象entityState设置为Modified,新学生应添加实体状态,然后保存更改。
这将添加新学生并将其链接到标准实体。
所以你的代码会喜欢这个伪代码
var standard4 = context.Standards.SingleOrDefault(s=> s.Id == 4);
if(standard4 != null)
{
var s=new student();
s.StudentName="Priyesh";
standard4.Students.Add(s); // this will set the State for Student to be Added
context.Entry(standard4).State = EntityState.Modified;
context.savechanges();
}
希望有所帮助。