2017-06-23 18 views

回答

1

我猜你是問有關如何自定義EntityFramework.DbContexts.Config

你可以從下面的代碼中的一些想法

public class CustomConfigurationContextFactory : IDbContextFactory<CustomConfigurationDbContext> 
{ 
    /// <summary> 
    /// A factory to create an instance of the StudentsContext 
    /// </summary> 
    /// <param name="connectionString"></param> 
    /// <returns></returns> 
    public static CustomConfigurationDbContext Create(string connectionString) 
    { 
     var optionsBuilder = new DbContextOptionsBuilder<ConfigurationDbContext>(); 

     optionsBuilder.UseSqlServer(connectionString); 

     var context = new CustomConfigurationDbContext(
      optionsBuilder.Options, 
      new ConfigurationStoreOptions()); 
     context.Database.EnsureCreated(); 

     return context; 
    } 

    public CustomConfigurationDbContext Create(DbContextFactoryOptions options) 
    { 
     var context = new CustomConfigurationDbContext(
      new DbContextOptions<ConfigurationDbContext>(), 
      new ConfigurationStoreOptions() 
     ); 

     context.Database.EnsureCreated(); 

     return context; 
    } 
    protected override void OnModelCreating(ModelBuilder builder) 
    { 
     builder.ConfigureClientContext(_storeOptions); 
     builder.Entity<Client>().HasIndex(x => x.ClientName).IsUnique(); 
    } 
} 

public class CustomConfigurationContextFactory : IDbContextFactory<CustomConfigurationDbContext> 
{ 
    public CustomConfigurationDbContext Create(DbContextFactoryOptions options) 
    { 
     var context = new CustomConfigurationDbContext(
      new DbContextOptions<ConfigurationDbContext>(), 
      new ConfigurationStoreOptions() 
     ); 

     context.Database.EnsureCreated(); 

     return context; 
    } 
} 

OnModelCreating您可以添加索引,你也可以添加自己的定製Dbset進入自定義配置dbcontext