EF Core Mapping EntityTypeConfiguration
В EF6 мы обычно можем использовать этот способ для настройки сущности.
public class AccountMap : EntityTypeConfiguration<Account>
{
public AccountMap()
{
ToTable("Account");
HasKey(a => a.Id);
Property(a => a.Username).HasMaxLength(50);
Property(a => a.Email).HasMaxLength(255);
Property(a => a.Name).HasMaxLength(255);
}
}
Как мы можем это сделать в EF Core, когда класс я унаследовал EntityTypeConfiguration, который не может найти класс.
Я загружаю исходный код EF Core из GitHub, я не могу его найти.
Может ли кто-нибудь помочь в этом?
Ответы
Ответ 1
Начиная с EF Core 2.0 существует IEntityTypeConfiguration<TEntity>
. Вы можете использовать это так:
class CustomerConfiguration : IEntityTypeConfiguration<Customer>
{
public void Configure(EntityTypeBuilder<Customer> builder)
{
builder.HasKey(c => c.AlternateKey);
builder.Property(c => c.Name).HasMaxLength(200);
}
}
...
// OnModelCreating
builder.ApplyConfiguration(new CustomerConfiguration());
Подробнее об этой и других новых функциях, представленных в 2.0, можно найти здесь.
Ответ 2
Вы можете достичь этого через несколько простых дополнительных типов:
internal static class ModelBuilderExtensions
{
public static void AddConfiguration<TEntity>(
this ModelBuilder modelBuilder,
DbEntityConfiguration<TEntity> entityConfiguration) where TEntity : class
{
modelBuilder.Entity<TEntity>(entityConfiguration.Configure);
}
}
internal abstract class DbEntityConfiguration<TEntity> where TEntity : class
{
public abstract void Configure(EntityTypeBuilder<TEntity> entity);
}
Использование:
internal class UserConfiguration : DbEntityConfiguration<UserDto>
{
public override void Configure(EntityTypeBuilder<UserDto> entity)
{
entity.ToTable("User");
entity.HasKey(c => c.Id);
entity.Property(c => c.Username).HasMaxLength(255).IsRequired();
// etc.
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.AddConfiguration(new UserConfiguration());
}
Ответ 3
В EF7 вы переопределяете OnModelCreating в классе DbContext, который вы реализуете.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Account>()
.ForRelational(builder => builder.Table("Account"))
.Property(value => value.Username).MaxLength(50)
.Property(value => value.Email).MaxLength(255)
.Property(value => value.Name).MaxLength(255);
}
Ответ 4
Используется последняя версия бета-версии 8.
Попробуйте следующее:
public class AccountMap
{
public AccountMap(EntityTypeBuilder<Account> entityBuilder)
{
entityBuilder.HasKey(x => x.AccountId);
entityBuilder.Property(x => x.AccountId).IsRequired();
entityBuilder.Property(x => x.Username).IsRequired().HasMaxLength(50);
}
}
Затем в вашем DbContext:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
new AccountMap(modelBuilder.Entity<Account>());
}
Ответ 5
Вы можете использовать отражение, чтобы делать что-то очень похожее на то, как они работают в EF6, с отдельным классом сопоставления для каждого объекта. Это работает в финале RC1:
Сначала создайте интерфейс для ваших типов сопоставления:
public interface IEntityTypeConfiguration<TEntityType> where TEntityType : class
{
void Map(EntityTypeBuilder<TEntityType> builder);
}
Затем создайте класс отображения для каждого из ваших объектов, например. для класса Person
:
public class PersonMap : IEntityTypeConfiguration<Person>
{
public void Map(EntityTypeBuilder<Person> builder)
{
builder.HasKey(x => x.Id);
builder.Property(x => x.Name).IsRequired().HasMaxLength(100);
}
}
Теперь магия отражения в OnModelCreating
в вашей реализации DbContext
:
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Interface that all of our Entity maps implement
var mappingInterface = typeof(IEntityTypeConfiguration<>);
// Types that do entity mapping
var mappingTypes = typeof(DataContext).GetTypeInfo().Assembly.GetTypes()
.Where(x => x.GetInterfaces().Any(y => y.GetTypeInfo().IsGenericType && y.GetGenericTypeDefinition() == mappingInterface));
// Get the generic Entity method of the ModelBuilder type
var entityMethod = typeof(ModelBuilder).GetMethods()
.Single(x => x.Name == "Entity" &&
x.IsGenericMethod &&
x.ReturnType.Name == "EntityTypeBuilder`1");
foreach (var mappingType in mappingTypes)
{
// Get the type of entity to be mapped
var genericTypeArg = mappingType.GetInterfaces().Single().GenericTypeArguments.Single();
// Get the method builder.Entity<TEntity>
var genericEntityMethod = entityMethod.MakeGenericMethod(genericTypeArg);
// Invoke builder.Entity<TEntity> to get a builder for the entity to be mapped
var entityBuilder = genericEntityMethod.Invoke(builder, null);
// Create the mapping type and do the mapping
var mapper = Activator.CreateInstance(mappingType);
mapper.GetType().GetMethod("Map").Invoke(mapper, new[] { entityBuilder });
}
}
Ответ 6
Это то, что я делаю в проекте, над которым я сейчас работаю.
public interface IEntityMappingConfiguration<T> where T : class
{
void Map(EntityTypeBuilder<T> builder);
}
public static class EntityMappingExtensions
{
public static ModelBuilder RegisterEntityMapping<TEntity, TMapping>(this ModelBuilder builder)
where TMapping : IEntityMappingConfiguration<TEntity>
where TEntity : class
{
var mapper = (IEntityMappingConfiguration<TEntity>)Activator.CreateInstance(typeof (TMapping));
mapper.Map(builder.Entity<TEntity>());
return builder;
}
}
Использование:
В вашем контексте Метод OnModelCreating:
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder
.RegisterEntityMapping<Card, CardMapping>()
.RegisterEntityMapping<User, UserMapping>();
}
Пример класса сопоставления:
public class UserMapping : IEntityMappingConfiguration<User>
{
public void Map(EntityTypeBuilder<User> builder)
{
builder.ToTable("User");
builder.HasKey(m => m.Id);
builder.Property(m => m.Id).HasColumnName("UserId");
builder.Property(m => m.FirstName).IsRequired().HasMaxLength(64);
builder.Property(m => m.LastName).IsRequired().HasMaxLength(64);
builder.Property(m => m.DateOfBirth);
builder.Property(m => m.MobileNumber).IsRequired(false);
}
}
Еще одна вещь, которую я хотел бы сделать, чтобы воспользоваться функцией сгибания Visual Studio 2015, - это объект, называемый "Пользователь", вы называете свой файл сопоставления "User.Mapping.cs", Visual Studio будет складывать файл в в проводнике решений, чтобы он содержался в файле класса сущности.
Ответ 7
Я закончил это решение:
public interface IEntityMappingConfiguration
{
void Map(ModelBuilder b);
}
public interface IEntityMappingConfiguration<T> : IEntityMappingConfiguration where T : class
{
void Map(EntityTypeBuilder<T> builder);
}
public abstract class EntityMappingConfiguration<T> : IEntityMappingConfiguration<T> where T : class
{
public abstract void Map(EntityTypeBuilder<T> b);
public void Map(ModelBuilder b)
{
Map(b.Entity<T>());
}
}
public static class ModelBuilderExtenions
{
private static IEnumerable<Type> GetMappingTypes(this Assembly assembly, Type mappingInterface)
{
return assembly.GetTypes().Where(x => !x.IsAbstract && x.GetInterfaces().Any(y => y.GetTypeInfo().IsGenericType && y.GetGenericTypeDefinition() == mappingInterface));
}
public static void AddEntityConfigurationsFromAssembly(this ModelBuilder modelBuilder, Assembly assembly)
{
var mappingTypes = assembly.GetMappingTypes(typeof (IEntityMappingConfiguration<>));
foreach (var config in mappingTypes.Select(Activator.CreateInstance).Cast<IEntityMappingConfiguration>())
{
config.Map(modelBuilder);
}
}
}
Использование примера:
public abstract class PersonConfiguration : EntityMappingConfiguration<Person>
{
public override void Map(EntityTypeBuilder<Person> b)
{
b.ToTable("Person", "HumanResources")
.HasKey(p => p.PersonID);
b.Property(p => p.FirstName).HasMaxLength(50).IsRequired();
b.Property(p => p.MiddleName).HasMaxLength(50);
b.Property(p => p.LastName).HasMaxLength(50).IsRequired();
}
}
и
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.AddEntityConfigurationsFromAssembly(GetType().Assembly);
}
Ответ 8
Просто внедрите IEntityTypeConfiguration
public abstract class EntityTypeConfiguration<TEntity> : IEntityTypeConfiguration<TEntity> where TEntity : class
{
public abstract void Configure(EntityTypeBuilder<TEntity> builder);
}
а затем добавьте его в контекст вашей сущности
public class ProductContext : DbContext, IDbContext
{
public ProductContext(DbContextOptions<ProductContext> options)
: base((DbContextOptions)options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfiguration(new ProductMap());
}
public DbSet<Entities.Product> Products { get; set; }
}
Ответ 9
Я прав?
public class SmartModelBuilder<T> where T : class {
private ModelBuilder _builder { get; set; }
private Action<EntityTypeBuilder<T>> _entityAction { get; set; }
public SmartModelBuilder(ModelBuilder builder, Action<EntityTypeBuilder<T>> entityAction)
{
this._builder = builder;
this._entityAction = entityAction;
this._builder.Entity<T>(_entityAction);
}
}
Я могу передать config:
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
new SmartModelBuilder<Blog>(builder, entity => entity.Property(b => b.Url).Required());
}
Ответ 10
Я придерживался аналогичного подхода к тому, как Microsoft внедрила ForSqlServerToTable
с использованием метода расширения...
требуется флаг partial, если вы хотите использовать одно имя класса в нескольких файлах
public class ConsignorUser
{
public int ConsignorId { get; set; }
public string UserId { get; set; }
public virtual Consignor Consignor { get; set; }
public virtual User User { get; set; }
}
public static partial class Entity_FluentMappings
{
public static EntityTypeBuilder<ConsignorUser> AddFluentMapping<TEntity> (
this EntityTypeBuilder<ConsignorUser> entityTypeBuilder)
where TEntity : ConsignorUser
{
entityTypeBuilder.HasKey(x => new { x.ConsignorId, x.UserId });
return entityTypeBuilder;
}
}
Затем в DataContext OnModelCreating сделайте свой вызов для каждого расширения...
public class DataContext : IdentityDbContext<User>
{
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
builder.Entity<ConsignorUser>().AddFluentMapping<ConsignorUser>();
builder.Entity<DealerUser>().AddFluentMapping<DealerUser>();
}
Таким образом мы следуем той же схеме, используемой другими методами построения.
Что вы делаете?
Ответ 11
Хорошо, вот проблема для улучшения в репозитории Eif7 Github: https://github.com/aspnet/EntityFramework/issues/2805
Вы можете отслеживать проблему прямо там, хотя ее все еще только в отставании без назначенного приоритета.
Ответ 12
У меня есть проект, который позволяет настраивать объекты вне DbContext.OnModelCreating
. Вы настраиваете каждый объект в отдельном классе, который наследует от StaticDotNet.EntityFrameworkCore.ModelConfiguration.EntityTypeConfiguration
Сначала вам нужно создать класс, который наследует от StaticDotNet.EntityFrameworkCore.ModelConfiguration.EntityTypeConfiguration<TEntity>
, где TEntity
- это класс, который вы хотите настроить.
using StaticDotNet.EntityFrameworkCore.ModelConfiguration;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
public class ExampleEntityConfiguration
: EntityTypeConfiguration<ExampleEntity>
{
public override void Configure( EntityTypeBuilder<ExampleEntity> builder )
{
//Add configuration just like you do in DbContext.OnModelCreating
}
}
Затем в вашем классе Startup вам просто нужно указать Entity Framework, где вы найдете все ваши классы конфигурации при настройке вашего DbContext.
using StaticDotNet.EntityFrameworkCore.ModelConfiguration;
public void ConfigureServices(IServiceCollection services)
{
Assembly[] assemblies = new Assembly[]
{
// Add your assembiles here.
};
services.AddDbContext<ExampleDbContext>( x => x
.AddEntityTypeConfigurations( assemblies )
);
}
Существует также возможность добавления конфигураций типов с использованием поставщика. В репо есть полная документация о том, как его использовать.
https://github.com/john-t-white/StaticDotNet.EntityFrameworkCore.ModelConfiguration
Ответ 13
В ядре ef нам нужно реализовать IEntityTypeConfiguration вместо EntityTypeConfiguration, в этом случае у нас есть полный доступ к DbContext modelBuilder, и мы можем использовать свободный API, но в ef core этот API немного отличается от предыдущих версий.
Вы можете найти более подробную информацию о конфигурации базовой модели ef на
https://www.learnentityframeworkcore.com/configuration/fluent-api
Ответ 14
В Entity Framework Core 2.0:
Я взял ответ Cocowalla и адаптировал его для версии 2.0:
public static class ModelBuilderExtenions
{
private static IEnumerable<Type> GetMappingTypes(this Assembly assembly, Type mappingInterface)
{
return assembly.GetTypes().Where(x => !x.IsAbstract && x.GetInterfaces().Any(y => y.GetTypeInfo().IsGenericType && y.GetGenericTypeDefinition() == mappingInterface));
}
public static void AddEntityConfigurationsFromAssembly(this ModelBuilder modelBuilder, Assembly assembly)
{
// Types that do entity mapping
var mappingTypes = assembly.GetMappingTypes(typeof(IEntityTypeConfiguration<>));
// Get the generic Entity method of the ModelBuilder type
var entityMethod = typeof(ModelBuilder).GetMethods()
.Single(x => x.Name == "Entity" &&
x.IsGenericMethod &&
x.ReturnType.Name == "EntityTypeBuilder'1");
foreach (var mappingType in mappingTypes)
{
// Get the type of entity to be mapped
var genericTypeArg = mappingType.GetInterfaces().Single().GenericTypeArguments.Single();
// Get the method builder.Entity<TEntity>
var genericEntityMethod = entityMethod.MakeGenericMethod(genericTypeArg);
// Invoke builder.Entity<TEntity> to get a builder for the entity to be mapped
var entityBuilder = genericEntityMethod.Invoke(modelBuilder, null);
// Create the mapping type and do the mapping
var mapper = Activator.CreateInstance(mappingType);
mapper.GetType().GetMethod("Configure").Invoke(mapper, new[] { entityBuilder });
}
}
}
И он использовался в DbContext следующим образом:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.AddEntityConfigurationsFromAssembly(GetType().Assembly);
}
И вот как вы создаете конфигурацию типа сущности для сущности:
public class UserUserRoleEntityTypeConfiguration : IEntityTypeConfiguration<UserUserRole>
{
public void Configure(EntityTypeBuilder<UserUserRole> builder)
{
builder.ToTable("UserUserRole");
// compound PK
builder.HasKey(p => new { p.UserId, p.UserRoleId });
}
}
Ответ 15
Начиная с EF Core 2.2 вы можете добавить все конфиги (классы, в которых реализован интерфейс IEntityTypeConfiguration) в одну строку в методе OnModelCreating в классе, который унаследован от класса DbContext
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//this will apply configs from separate classes which implemented IEntityTypeConfiguration<T>
modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
}
И, как уже упоминалось в предыдущем ответе, начиная с EF Core 2.0, вы можете реализовать интерфейс IEntityTypeConfiguration, настроить конфигурацию отображения с помощью FluentAPI в методе Configure.
public class QuestionAnswerConfig : IEntityTypeConfiguration<QuestionAnswer>
{
public void Configure(EntityTypeBuilder<QuestionAnswer> builder)
{
builder
.HasKey(bc => new { bc.QuestionId, bc.AnswerId });
builder
.HasOne(bc => bc.Question)
.WithMany(b => b.QuestionAnswers)
.HasForeignKey(bc => bc.QuestionId);
builder
.HasOne(bc => bc.Answer)
.WithMany(c => c.QuestionAnswers)
.HasForeignKey(bc => bc.AnswerId);
}
}