我正在使用EF MVC。 在我的模型中,我有一个要变成学生的用户,我需要为学生分配一些字段。我正在制定一种将用户批量分配给学生的方法,我需要为学生分配一些字段。这是我目前正在做的
var students = db.Students.AsQueryable();
var users = db.Users.Where(u => !students.Any(s => s.UserId == u.Id) ).ToList();//exclude current students from users
Student[] filteredStudents = new Student[users.Count];
var i = 0;
foreach (var user in users)
{
filteredStudents[i] = (Student)user;
filteredStudents[i].CreatedDate = DateTime.Now;
filteredStudents[i].ModifiedDate = DateTime.Now;
i++;
}
db.Students.AddRange(filteredStudents);
在我的学生课上
public static explicit operator Student(User user)
{
Student student = new Student() { UserId = user.Id, ApplicationUser = user };
return student;
}
我觉得我应该缺少一些更优雅的东西。 我看到过zip,但我想要类似于EF表示法的东西,例如此伪代码
var finalList = students.AssignMany(UserId = Id, this.User = User, Users.Select(Id, User));
这可能吗?
答案 0 :(得分:0)
通过使用ConvertAll(),您可以使用将用户带回并返回学生并将其作为参数传递的函数。 ConvertAll
函数将返回学生列表。
var users = db.Users.Where(u => !students.Any(s => s.UserId == u.Id) ).ToList();//exclude current students from users
var newStudents = users.ConvertAll(new Converter<User, Student>(UserToStudent)); //newStudents will contain the converted users, to do with what you want.
......snip.....
function static Student UserToStudent(User toConvert){
Student student = new Student(){UserId = toConvert.Id, ApplicationUser = toConvert, CreatedDate = DateTime.Now, ModifiedDate = DateTime.Now};
return student;
}