Entity Framework - 获取最新条目的数据库映射

Entity Framework - Database mapping to get latest entry

想象一个有两个 table 的数据库:BlogPost。在我的场景中,Posttable 有一个名为 CreateDate 的 属性,它等于 Post 的创建日期。我在 BlogPost 之间有一个关系,其中一个 Blog 可以包含许多 Posts,我希望有一个名为 [=21] 的 C# 模型 属性 =].这是一个例子:

public class Blog
{
    public int Id { get; set; }
    public string Title { get; set; }

    public virtual List<Post> Posts { get; set; }
    public virtual Post LatestPost { get; set; }
}

我希望能够获取此特定 Blog 的最新 Post,按 Post.CreatedDate 排序。我可以看到,如果我要重写上述方法,我可以在 Dbcontext.OnModelCreating() 中按照我的意愿进行映射。我只是不太确定如何制作此映射。我是否可以这样做并获得最新的 Post for a Blog?

为此,您的 Blog 应该有 Posts 的外键 ,例如:

public class Blog
{
    public int Id { get; set; }
    public string Title { get; set; }
    public int LatestPostId? { get; set; }

    public virtual ICollection<Post> Posts { get; set; }
    public virtual Post LatestPost { get; set; }
}

然后在 OnModelCreating 方法中你可以像这样映射它:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Blog>()
        .HasOptional(m => m.LatestPost)
        .WithMany()
        .HasForeignKey(m => m.LatestPostId);
}

但我建议您在需要时加载 LatestPost:

Post latestPost = myContext.Posts
    .Where(m => m.BlogId == blogId)
    .OrderByDescending(m => m.CreatedDate)
    .FirstOrDefault();

此外,您可以使 LatestPost 未映射并将其配置为从数据库加载数据:

public class Blog
{
    public int Id { get; set; }
    public string Title { get; set; }       

    public virtual ICollection<Post> Posts { get; set; }
    public virtual Post LatestPost
    {
        get
        {
            return Posts
                .OrderByDescending(m => m.CreatedDate)
                .FirstOrDefault();
        }
    }
}

不要忘记忽略 OnModelCreating 中的 LatestPost:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Blog>()
        .Ignore(m => m.LatestPost);
}

此外,您可以通过添加 NotMapped 属性忽略此 属性:

public class Blog
{
    ....

    [NotMapped]
    public virtual Post LatestPost
    .....
}