转载请注明出处:http://www.cnblogs.com/zhiyong-ITNote/
一直不习惯linq的扩展方法,每次用的时候,贼不顺手,尤其是查数据的时候,这不更新个数据库这么简单地需求都搞了一个小时(好吧,也有心不在焉的因素)。总结了一下,代码如下:
private readonly PracticeDevDbContext _context;public DefaultController(PracticeDevDbContext context){ _context = context;}public IActionResult Index(){ ListnewUsers = new List { new User{ Email = "22222", Other="w w w w w", UserName="user 2"}, new User{ Email = "33333", Other="e e e e e", UserName="user 3"}, new User{ Email = "44444", Other="r r r r r", UserName="user 4"}, new User{ Email = "55555", Other="t t t t t ", UserName="user 5"}, new User{ Email = "66666", Other="y y y y y", UserName="user 6"}, new User{ Email = "77777", Other="u u u u u", UserName="user 7"}, }; List oldUsers = _context.Users.ToList(); foreach(var user in newUsers) { var tempUser = oldUsers.Where(o => o.Email == user.Email).FirstOrDefault(); if(tempUser != null) { tempUser.Other = user.Other; tempUser.UserName = user.UserName; _context.Users.Update(tempUser); } else { user.Id = new Random().Next(5,20); _context.Users.Add(user); } } _context.SaveChanges(); return Content("我的测试");}
其实就是一个这么简单地实现,搞了大半天。首先应该或许一个实体对象,然后在做字段更新,最后使用Update更新,并提交到数据库
参考:http://www.cnblogs.com/zhouyukai/p/7451534.html
转载请注明出处:http://www.cnblogs.com/zhiyong-ITNote/