在使用 inheritance in EF Core 时,我正在努力避免重复投影逻辑.
这是我的场景:我有三种类型:
Lesson
(这是一个抽象类)(属性: Id
、 Title
等)ArticleLesson
(继承自 Lesson
)(属性: Content
、 TotalWoddsCount
等) VideoLesson
(继承自 Lesson
)(属性: VideoUrl
、 Duration
等) EF Core 几乎可以正确处理所有内容,我使用的是默认的 Table-Per-Hierarchy (TPH) 方法。
当我想从数据库中检索类(class)并且我需要一些
ArticleLesson
之间的共享列时,就会出现问题。和 VideoLesson
(即 Lesson
的一些属性),以及一些特定于 ArticleLesson
的属性或 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
和 Title
,但在现实世界中,您可以拥有数十个;并且不得不像这样重复所有这些将是一个小时。有什么办法可以让这个投影表达更简洁,避免重复?
最佳答案
您可以在 LessonDto
中添加一个构造函数, ArticleLessonDto
和 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();
关于c# - 使用 EF Core 继承时如何避免重复属性投影?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67322631/