//想想18,也按这种思路改一改先标注newUserExpand.User删除再标注newUserExpand删除 //也可以达到预期 public void Method20() { //准备一条数据 using (var context = new DefaultDbContext()) { var user = new SysUser() { UserName = "******", Password = "******", UserExpand = new SysUserExpand { ExpandValue1 = "user20的补充" } }; context.Entry(user).State = System.Data.Entity.EntityState.Added; context.SaveChanges(); } SysUserExpand newUserExpand = null; using (var context = new DefaultDbContext()) { newUserExpand = context.Set <SysUserExpand>().Include(p => p.User) .SingleOrDefault(o => o.ExpandValue1 == "user20的补充"); } using (var context = new DefaultDbContext()) { context.Entry(newUserExpand.User).State = System.Data.Entity.EntityState.Deleted; context.Entry(newUserExpand).State = System.Data.Entity.EntityState.Deleted; context.SaveChanges(); } }
//一步新增,通过UserExpand仓储 public void Method101() { var repo = new UserExpandRepository(); var userExpand = new SysUserExpand() { ExpandValue1 = "user101的补充", User = new SysUser() { UserName = "******", Password = "******" } }; repo.Insert(userExpand); }
//1、2都是一次定义包含两个对象,也可以两步定义 public void Method3() { using (var context = new DefaultDbContext()) { var user = new SysUser() { UserName = "******", Password = "******", }; var userExpand = new SysUserExpand() { ExpandValue1 = "user3的补充" }; user.UserExpand = userExpand; context.Entry(user).State = System.Data.Entity.EntityState.Added; context.SaveChanges(); } }
//通过新增UserExpand对象,然后设置UserExpand新增 //不报错,但是达不到预期效果,同时新增了新的User和新的UserExpand //注意:这里新增UserExpand是包含id和导航User的 public void Method5() { //准备一条数据 using (var context = new DefaultDbContext()) { var user = new SysUser() { UserName = "******", Password = "******", }; context.Entry(user).State = System.Data.Entity.EntityState.Added; context.SaveChanges(); } SysUser newUser = null; using (var context = new DefaultDbContext()) { newUser = context.Set <SysUser>().SingleOrDefault(o => o.UserName == "user5"); } SysUserExpand newUserExpand = new SysUserExpand { Id = newUser.Id, User = newUser, ExpandValue1 = "user5的补充" }; newUser.UserExpand = newUserExpand; using (var context = new DefaultDbContext()) { context.Entry(newUserExpand).State = System.Data.Entity.EntityState.Added; context.SaveChanges(); } }