要做到這一點,你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();
}
}
}
不要忘記忽略LatestPost
在OnModelCreating
:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.Ignore(m => m.LatestPost);
}
此外,您可以通過添加忽略此屬性NotMapped
屬性:
public class Blog
{
....
[NotMapped]
public virtual Post LatestPost
.....
}
好回答。我雖然只是在需要的時候加載它,但由於某種原因,我的頭說這是不好的做法......謝謝你的答案。 – Detilium
@Detilium,我很高興它有幫助 –