Fluent API with Aaron to Database Mapping
In the previous part, we created a project named
Aaron.Domain with 2 classes are
"Catalog" and
"Article". And this part, we shall discuss how to use Fluent API with Aaron to database mapping.
First, I create a project named
Aaron.Data.Mapping, and then to
install a package Aaron.Core by nuget, be like
Aaron.Domain, or select "Set as StartUp Project" and then run the
"Package Manager Console", type command:
Install-Package Aaron.Core
And then,
"CatalogMap" and
"ArticleMap" classes be created, as follows:
In CatalogMap class:
using System.Collections.Generic;
using Aaron.Core;
using Aaron.Domain.Catalogs;
namespace Aaron.Data.Mapping
{
public class CatalogMap : BaseEntityTypeConfiguration<Catalog, int>
{
public CatalogMap()
: base()
{
this.Property(x => x.CatalogName).HasMaxLength(255);
this.Property(x => x.Description).IsMaxLength();
}
}
}
In ArticleMap class:
using System;
using System.Collections.Generic;
using Aaron.Core;
using Aaron.Domain.Articles;
namespace Aaron.Data.Mapping
{
public class ArticleMap : SEOEntityTypeConfiguration<Article, Guid>
{
public ArticleMap()
: base()
{
this.Property(x => x.Title).HasMaxLength(255);
this.Property(x => x.Published);
this.HasRequired(a => a.Catalog)
.WithMany(c => c.Articles)
.HasForeignKey(ac => ac.CatalogId);
}
}
}
2 classes above inherit from BaseEntityTypeConfiguration<T,TKey> and SEOEntityTypeConfiguration<T, TKey> with
T is a class inherits from BaseEntity or SEOEntity and
TKey is type of Identity as BaseEntity<TKey>:
Remember, the
"base" keyword at constructor; it's a parent constructor with argument that is a boolean type named
"inherited", and default is
false. In this case, any domain class inherits from another domain class; therefore, argument
"inherited" would be
"true". (I will discuss the later sections)
public ArticleMap() : base([inherited = false]) { // any code here... }
Summary, this part provides a concept of
BaseEntityTypeConfiguration<T, TKey> and
SEOEntityTypeConfiguration<T, TKey> and using for database mapping. And the next part, we discuss about
Runtime demo with custom database based on Domain models and mapping.