如何通过linq和实体框架

时间:2017-10-10 23:07:01

标签: c# entity-framework

是否有在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;
}

1 个答案:

答案 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;
}