考虑到博客数据模型:
Blog:
int Id
ICollection<Post> Posts
Post:
int Id
int BlogId
DateTime Date然后加载博客的最新发布日期(LatestPostDate),并绑定到UI,同时由上下文跟踪它们。
有一些解决方案,例如使用DTO,但是结果实体不被上下文跟踪。此外,我还可以将LatestPostDate设置为NotMapped,定义表值函数,并在DbSet上应用SqlQuery。虽然,NotMapped字段不是以这种方式加载的。
什么是最佳做法?
我尽量不将列添加到表中,也避免在加载后计算值。
发布于 2017-11-17 15:55:58
最佳实践是处理ViewModel中的显示问题。
但是,由于您不想将实体映射到另一个类,我们首先来看看[NotMapped]变量,使用LINQ来计算最新的post日期,而不是普通的SQL。
using System.Linq;
public class Blog {
public int Id { get; set; }
public virtual ICollection<Post> Posts { get; set; }
[NotMapped]
public DateTime? LatestPostDate {
get {
return Posts.OrderBy(p => p.Date).LastOrDefault()?.Date;
}
}
}这样,只有在访问属性LatestPostDate (可能在UI呈现期间)时才计算值。您可以通过急装 ( Posts )减少DB访问的次数,尽管这将增加您正在使用的数据集的大小。
var blogs = _dbContext.Blogs.Include(b => b.Posts).ToArray();但是,如果使用ViewModel,则可以一次填充LatestPostDate:
public class BlogViewModel {
public int Id { get; set; }
public DateTime? LatestPostDate { get; set; }
}
var viewModels = _dbContext.Blogs.Select(b => new BlogViewModel {
Id = b.Id,
LatestPostDate = b.Posts.OrderBy(p => p.Date).LastOrDefault()?.Date;
}).ToArray();考虑到上下文没有跟踪ViewModel :在编辑usecase中,再次使用ViewModel提供的Id加载实体,并映射更新的属性。这使您完全控制应该可编辑的属性。作为一种奖励,ViewModel是进行输入验证、格式化等的好地方。
https://stackoverflow.com/questions/47349505
复制相似问题