Skip to content

2 Models

Emmanuel D edited this page Nov 9, 2020 · 1 revision

The framework rely on models that will be transferred from one layer to another. It's better to host all models into a separate project.

Models should be a copy of your database schema, or at least a subset. Each models should inherit from IBaseEntity and implement method

public object DatabaseID { get => Id; }

The DatabaseID should point to your primary key property. Its type is object to support all type of primary key.

Using EF code first is not a big deal for this task.

For EF database first, I recommend using EF PowerTools and do some tweaks. In EF PowerTools, you have the option to only generate Entities (and no DBContext) and take care not add any EF dependencies. If you're using C# code template, customize the file CSharpEntityType\Class.hbs to add IBaseEntity inheritance.

For each generated class, create another file that will host a part of partial class and where interface IBaseEntity should be implemented. Split your class on different files to ensure that on next tool run, your content will not be overwritten.

Aside the models, you might also create validators for each of your models. Validator use FluentValidation behind the scene and will automatically be called on the objet creation or update.

public class MyModelValidator : AbstractValidator<MyModel>
{
    public MyModelValidator()
    {
        RuleFor(x => x.Name).MinimumLength(2).MaximumLength(50).WithMessage("Name of MyModel should be between 2 and 50 characters");
    }
}

For models and mapping, IMapFrom helps you to define automapper profile in the target class. The Mapping method is not mandatory if your mapping is implicit.

public class SmallCarInfo : IMapFrom<Car>
{
    public long ID { get; set; }
    public string Name { get; set; }
    public string CustomField { get; set; }

    public void Mapping(Profile profile)
    {
        if (profile != null)
        {
            profile.CreateMap<Car, SmallCarInfo>()
                .ForMember(dest => dest.CustomField , src => src.MapFrom(x => .... ))
        }
    }
}
Clone this wiki locally