Код: Выделить всё
public interface IEntity
{
// Identity column.
public long Id { get; set; }
public bool IsAuditable { get; set; }
public DateTime DateTimeCreated { get; set; }
public DateTime? DateTimeModified { get; set; }
}
public interface IEntity:
IEntity
where TEntity: class, IEntity, IEntity, new()
{ }
Рассмотрим следующую иерархию:
Код: Выделить всё
// Acts as a based class for all entities in the DbContext.
public class EntityBase
IEntity
where TEntity : class, IEntity, IEntity, new()
{
// Identity column.
public long Id { get; set; }
public bool IsAuditable { get; set; }
public DateTime DateTimeCreated { get; set; }
public DateTime? DateTimeModified { get; set; }
}
public class DocumentBase : EntityBase
{
public string Name { get; set; }
}
public class ElementBase : EntityBase
{
public string Name { get; set; }
}
// Should represent a database table with all properties
// from the base class but without a discriminator column.
public class Document : DocumentBase
{
public virtual ICollection Elements { get; set; } = [];
}
// Should represent a database table with all properties
// from the base class but without a discriminator column.
public class Element : ElementBase
{
public long DocumentId { get; set; }
public virtual Document Document { get; set; }
}
public class ApplicationDbContext : DbContext
{
public DbSet Documents { get; set; }
public DbSet Elements { get; set; }
}
- Ни DocumentBase, ни ElementBase не должны должны быть абстрактными (при необходимости у нас должна быть возможность пометить их как абстрактные)
- DbContext не должен ничего знать об этих базовых классах, кроме их свойств (как если бы они были объявлены в конкретных классах)
- Единственное сходство между различными сущности сойдутся в ConcreteEntity > ConcreteEntityBase > EntityBase. Никакие другие пути рассматриваться не должны
- (Id, IsAuditable, DateTimeCreated, DateTimeModified, Name, Elements)
Код: Выделить всё
Document - (Id, IsAuditable, DateTimeCreated, DateTimeModified, Name, Document, DocumentId)
Код: Выделить всё
Element
Обратите внимание, что этот вопрос не касается выбора дизайна. или мой подход соответствует лучшим практикам. Я просто хочу знать, можно ли этого добиться с помощью EF9, и если да, то какая конфигурация необходима.
Подробнее здесь: https://stackoverflow.com/questions/792 ... code-first
Мобильная версия