-
Notifications
You must be signed in to change notification settings - Fork 393
11 efcore pemelo codefirst
This article describes how to map entities to the database in the ADNC framework using the Code First pattern.
Create your entity class in the Entities directory of the Adnc.Cus.Repository project.
- For Classic 3-tier architecture, inherit from
EfEntity. - For DDD architecture, inherit from
AggregateRootorDomainEntity.
namespace Adnc.Cus.Entities
{
public class Customer : EfFullAuditEntity
{
public string Account { get; set; }
public string Nickname { get; set; }
public string Realname { get; set; }
public virtual CustomerFinance FinanceInfo { get; set; }
public virtual ICollection<CustomerTransactionLog> TransactionLogs { get; set; }
}
}Create a mapping class in the Entities/Config directory using Fluent API.
namespace Adnc.Cus.Entities.Config
{
public class CustomerConfig : EntityTypeConfiguration<Customer>
{
public override void Configure(EntityTypeBuilder<Customer> builder)
{
base.Configure(builder);
builder.HasOne(d => d.FinanceInfo)...;
builder.Property(x => x.Account).IsRequired().HasMaxLength(50);
}
}
}Note: EntityTypeConfiguration<TEntity> is a base class in ADNC that handles common mapping concerns like soft deletes, concurrency tokens (RowVersion), and primary keys.
Define an EntityInfo class implementing IEntityInfo. This class is used to scan the assembly for entities.
namespace Adnc.Cus.Entities
{
public class EntityInfo : AbstractEntityInfo
{
public override IEnumerable<EntityTypeInfo> GetEntitiesTypeInfo()
{
return base.GetEntityTypes(this.GetType().Assembly)
.Select(x => new EntityTypeInfo() { Type = x });
}
}
}The EntityInfo is registered automatically via the services.AddEfCoreContextWithRepositories() extension method during application startup.
- Set the API project (e.g.,
Adnc.Cus.WebApi) as the Startup Project. - Open the Package Manager Console.
- Set the default project to the Migrations project (e.g.,
Adnc.Cus.Migrations). - Run
add-migration InitialCreate. - Run
update-database.
ADNC uses a custom AdncDbContext that automatically applies configurations:
- Table Naming: Automatically converts table and column names to lowercase.
-
Comments: Reads
<summary>tags from your C# code and applies them as database comments. -
Fluent API: Automatically loads all configurations from the assembly via
modelBuilder.ApplyConfigurationsFromAssembly.
If this helps, please Star & Fork.
- Official Website: https://aspdotnetcore.net
- Online Demo: https://online.aspdotnetcore.net
- Documentation: https://docs.aspdotnetcore.net
- Code Generator: https://code.aspdotnetcore.net