[英]Entity Framework Code First - Configuration in another file
What is the best way to separate the mapping of tables to entities using the Fluent API so that it is all in a separate class and not inline in the OnModelCreating method? 使用Fluent API将表映射到实体的最佳方法是什么,这样它们都在一个单独的类中,而不是在OnModelCreating方法中内联?
What I am doing currently: 我目前在做什么:
public class FooContext : DbContext {
// ...
protected override OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Entity<Foo>().Property( ... );
// ...
}
}
What i want: 我想要的是:
public class FooContext : DbContext {
// ...
protected override OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.LoadConfiguration(SomeConfigurationBootstrapperClass);
}
}
How do you do this? 你怎么做到这一点? I am using C#. 我正在使用C#。
You will want to create a class that inherits from the EntityTypeConfiguration class, like so: 您将需要创建一个继承自EntityTypeConfiguration类的类,如下所示:
public class FooConfiguration : EntityTypeConfiguration<Foo>
{
public FooConfiguration()
{
// Configuration goes here...
}
}
Then you can load the configuration class as part of the context like so: 然后,您可以将配置类作为上下文的一部分加载,如下所示:
public class FooContext : DbContext
{
protected override OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new FooConfiguration());
}
}
This article goes into greater detail on using configuration classes. 本文将详细介绍如何使用配置类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.