public void Update(IEnumerable <PostMetasInfo> infos, int postid) { using (MVCBlogContext Context = new MVCBlogContext()) { if (infos != null && infos.Count() > 0) { var relations = Context.PostMetaRelation.Where(x => x.PostId == postid).ToList(); foreach (PostMetasInfo info in infos) { if (info.Id != 0) { var exists = relations.FirstOrDefault(x => x.PostMetaId == info.Id); if (exists != null) { exists.IsDelete = false; } else { exists = new PostMetaRelation() { PostId = postid, PostMetaId = info.Id }; Context.PostMetaRelation.Add(exists); } Update(info); } else { var add = new PostMetasInfo() { Name = info.Name }; add = Context.PostMetasInfo.Add(add); Context.SaveChanges(); var relation = new PostMetaRelation() { PostId = postid, PostMetaId = add.Id }; Context.PostMetaRelation.Add(relation); } } var ids = infos.Select(s => s.Id); var removes = Context.PostMetaRelation.Where(x => x.PostId == postid && !ids.Contains(x.PostMetaId)).ToList(); foreach (var item in removes) { item.IsDelete = true; } Context.SaveChanges(); } } }
public void Insert(IEnumerable <PostMetasInfo> infos, int postid) { using (MVCBlogContext Context = new MVCBlogContext()) { //throw new NotImplementedException(); if (infos != null) { foreach (PostMetasInfo info in infos) { if (info.Id != 0) { var relation = Context.PostMetaRelation.FirstOrDefault(x => x.PostId == postid && x.PostMetaId == info.Id); if (relation != null) { relation.IsDelete = false; } else { relation = new PostMetaRelation() { PostId = postid, PostMetaId = info.Id }; Context.PostMetaRelation.Add(relation); } } else { var entity = Context.PostMetasInfo.Add(info); Context.SaveChanges(); var relation = new PostMetaRelation() { PostId = postid, PostMetaId = entity.Id }; Context.PostMetaRelation.Add(relation); } } Context.SaveChanges(); } } }