是否有在Entity Framework中查找或添加元素的功能?
例如,替换类似的东西:public static Student findOrAdd(ModelSchool modelSchool,Student student)
{
var newStudent = modelSchool.Students.Where(s => s.Name == student.Name).FirstOrDefault<Student>();
if (newStudent == null)
{
newStudent = modelSchool.Students.Add(student);
}
return newStudent;
}
答案 0 :(得分:0)
你有它。您可以简单地使用LINQ语句,如下所示。为确保正确创建新学生,您需要在SaveChanges
上调用DbContext
方法,我假设您的ModelSchool
是。
public static Student findOrAdd(ModelSchool modelSchool,Student student)
{
var newStudent = modelSchool.Students.FirstOrDefault(s => s.Name == student.Name);
if (newStudent == null)
{
newStudent = modelSchool.Students.Add(student);
modelSchool.SaveChanges();
}
return newStudent;
}