我正在努力解决如何在使用时避免重复投影逻辑EF Core 中的继承 https://learn.microsoft.com/en-us/ef/core/modeling/inheritance.
这是我的情况:我有三种类型:
-
Lesson
(这是一个抽象类)(属性:Id
, Title
, etc.)
-
ArticleLesson
(继承自Lesson
) (特性:Content
, TotalWoddsCount
, etc.)
-
VideoLesson
(继承自Lesson
) (特性:VideoUrl
, Duration
, etc.)
几乎所有事情都由 EF Core 正确处理,并且我使用默认的每个层次结构表 (TPH) 方法。
当我想从数据库中检索课程并且需要之间的一些共享列时,就会出现问题ArticleLesson
and VideoLesson
(即一些属性Lesson
),另外,还有一些特定于两者的属性ArticleLesson
or VideoLesson
。这是我想出的表达方式:
var r1 = dbContext.Lessons.Select<Lesson, LessonDto>(l =>
l is ArticleLesson
? new ArticleLessonDto
{
Id = l.Id, // This is repeated below
Title = l.Title, // This is repeated below
// ...other properties that I would have to repeat below
Content = (l as ArticleLesson).Content,
}
: l is VideoLesson
? new VideoLessonDto
{
Id = l.Id, // This is repeated above
Title = l.Title, // This is repeated above
// ...other properties that I would have to repeat above
VideoUrl = (l as VideoLesson).VideoUrl,
}
: null
)
.ToList();
正如您所看到的,我重复了共享属性部分两次。此示例中仅重复了 2 个属性,Id
and Title
,但在现实世界中您可以拥有数十个;必须像这样重复所有这些将是一个h。
有没有办法让这个投影表达更加简洁,避免重复呢?
您可以将构造函数添加到您的LessonDto
, ArticleLessonDto
and VideoLessonDto
接受不同的共享属性。
public class LessonDto
{
public LessonDto(int id, ... other)
{
Id = id;
// ...
}
public int Id { get; set; }
}
public class ArticleLessonDto : LessonDto
{
public ArticleLessonDto(LessonDto dto) : base(dto.Id)
{
}
public string Content { get; set; }
}
var r1 = dbContext.Lessons
.Select(l => new
{
dto = new LessonDto(l.Id, ... other),
full = l
})
.Select(row => row.full is ArticleLesson
? new ArticleLessonDto(row.dto)
{
Content = (row.full as ArticleLesson).Content,
}
: row.full is VideoLesson
? new VideoLessonDto(row.dto)
{
VideoUrl = (row.full as VideoLesson).VideoUrl,
}
: (LessonDto)null
)
.ToList();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)