private static Blog GetBlog(int blogId) { Blog blog = null; using (var db = new CtContext()) { blog = db.Blogs.FirstOrDefault(x => x.BlogId == blogId); } return(blog); }
private static Post GetPost(int postId) { Post post = null; using (var db = new CtContext()) { post = db.Posts.FirstOrDefault(x => x.PostId == postId); } return(post); }
private static void UpdateBlogAndTheirPost() { using (var db = new CtContext()) { var blogs = db.Blogs.Include(x => x.Posts).ToList(); blogs.ForEach(x => { x.Rating = 170; x.Posts.ForEach(y => { y.Content = y.Content + DateTime.Now.ToString(); }); db.Entry(x).State = EntityState.Modified; }); db.SaveChanges(); } }
private static void AddEntity() { using (var db = new CtContext()) { if (!db.Blogs.Any()) { db.Blogs.Add(new Blog { Url = "http://sample.com", Rating = 5, Posts = new List <Post> { new Post { Content = "1", Title = "1" } } }); db.SaveChanges(); } } }
private static List <T> GetHistory <T>(T entity) { var result = new List <T>(); var entityName = entity.GetType().FullName; var postHistories = new List <ChangeLog>(); using (var db = new CtContext()) { var primaryKey = GetPrimaryKeyValue(entity); postHistories = db.ChangeLogs .Where(x => x.PrimaryKeyValue == primaryKey && x.EntityName == entityName) .OrderByDescending(x => x.CreatedDate).ToList(); } var groupedHistories = postHistories.GroupBy(x => x.BatchId).Select(x => new { BatchId = x.Key, Histories = x.ToList() }).ToList(); var tempPost = entity.Clone(); foreach (var gh in groupedHistories) { foreach (var h in gh.Histories) { PropertyInfo propertyInfo = tempPost.GetType().GetProperty(h.PropertyName); Type t = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType; object safeValue = (h.OldValue == null) ? null : Convert.ChangeType(h.OldValue, t); propertyInfo.SetValue(tempPost, safeValue, null); } result.Add(tempPost); tempPost = tempPost.Clone(); } result.Insert(0, entity); return(result); }