Does Entity Framework Code First allow for fluent mappings in separate files?

荒凉一梦 提交于 2019-12-03 12:26:05

You can create one configuration class per entity derived from EntityTypeConfiguration<TEntity> and put these classes into separate files. In your derived DbContext you add instances of those configuration classes to the model builder. Example:

public class UserConfiguration : EntityTypeConfiguration<User>
{
    public UserConfiguration()
    {
        HasKey(u => u.UserName);

        Property(u => u.UserName)
            .HasMaxLength(50)
            .IsRequired();

        // etc.
    }
}

public class RoleConfiguration : EntityTypeConfiguration<Role>
{
    public RoleConfiguration()
    {
        HasKey(r => r.RoleName);

        // etc.
    }
}

Derived context:

public class MyContext : DbContext
{
    //...

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new UserConfiguration());
        modelBuilder.Configurations.Add(new RoleConfiguration());
    }
}

There is also a ComplexTypeConfiguration<T> you can derive from to configure complex types.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!