我有2张桌子。首先是“文档”,它与第二个具有“ hasMany”关系的表2“ DocumentVersions”相关。我正在尝试获取文档并将表2中的最后一行包含在表1中的公共虚拟DocumentVersion属性中。
在我的存储库中,这就是我尝试获取的方式
return _dcmsContext.Documents
.Include(d => d.DocumentCategory)
.Include(d => d.Project)
.Include(d => d.Department)
.Include(d => d.Author)
.Include(d => (d.DocumentVersions.LastOrDefault()))
.Where(d =>
d.IsActive == isActive &&
projectIds.Contains(d.ProjectId) &&
(d.RestrictByDepartment == false || d.DepartmentId == user.DepartmentId) &&
(d.RestrictByLocation == false || d.ProjectId == user.ProjectId));
上下文:
modelBuilder.Entity<Document>(entity =>
{
entity.HasMany(d => d.DocumentVersions);
entity.HasOne(d => d.DocumentCategory);
entity.HasOne(d => d.Department);
entity.HasOne(d => d.Project);
entity.HasOne(d => d.Author);
entity.HasOne(d => d.LastestVersion);
});
文档类(表1):
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int DocumentId { get; set; }
[NotMapped]
public virtual DocumentVersion LastestVersion { get; set; }
DocumentVersions类(表2):
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int DocumentVersionId { get; set; }
[ForeignKey("Document")]
public int DocumentId { get; set; }
[Required]
public float Version { get; set; }
我还尝试了多种方法来实现此目的,如下面的代码,但没有运气。
.Include(d => (d.DocumentVersions.LastOrDefault() as d.LatestVersion))
我正在尝试像这样:
[
{
"documentId": 1,
"title": "Sample",
"description": "test",
"restrictByDepartment": false,
"latestVersion": {
"documentId": 3,
"documentVersionId": 8,
"version": 5
}
]