c# – 如何在__MigrationHistory表中添加其他列?
发布时间:2020-12-16 02:02:02 所属栏目:百科 来源:网络整理
导读:根据 Customizing the Migrations History Table,我应该能够添加一列,但是我无法找到有关如何实际添加新列的任何示例. 我很担心放置实际属性的位置以及如何将其配置到现有的__MigrationHistory表.从文档中,我可以自定义表配置. protected override void OnMo
根据
Customizing the Migrations History Table,我应该能够添加一列,但是我无法找到有关如何实际添加新列的任何示例.
我很担心放置实际属性的位置以及如何将其配置到现有的__MigrationHistory表.从文档中,我可以自定义表配置. protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<HistoryRow>().ToTable(tableName: "MigrationHistory",schemaName: "admin"); modelBuilder.Entity<HistoryRow>().Property(p => p.MigrationId).HasColumnName("Migration_ID"); } …但我无法修改HistoryRow实体. 我应该根据HistoryRow实体添加新的派生类型吗? 解决方法
首先,您需要为历史记录行实体创建一个新类.例如:
public sealed class MyHistoryRow : HistoryRow { //We will just add a text column public string MyColumn { get; set; } } 接下来我们需要一个上下文,就像我们对普通EF操作一样,但是这次我们继承了HistoryContext: public class MyHistoryContext : HistoryContext { //We have to 'new' this as we are overriding the DbSet type public new DbSet<MyHistoryRow> History { get; set; } public MyHistoryContext(DbConnection dbConnection,string defaultSchema) : base(dbConnection,defaultSchema) { } //This part isn't needed but shows what you can do protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); //Rename the table and put it in a different schema. Our new table //will be called 'admin.MigrationHistory' modelBuilder.Entity<MyHistoryRow>().ToTable(tableName: "MigrationHistory",schemaName: "admin"); //Rename one of the columns for fun modelBuilder.Entity<MyHistoryRow>().Property(p => p.MigrationId).HasColumnName("Migration_ID"); } } 现在要连接它们,我们需要配置它,所以首先我们设置配置: public class MyConfiguration : DbConfiguration { public MyConfiguration() { //Set our new history context to be the one that gets used this.SetHistoryContext("System.Data.SqlClient",(connection,defaultSchema) => new MyHistoryContext(connection,defaultSchema)); } } 最后,通过修改我们的web.config来使配置适用:(您必须填写自己的命名空间和应用程序程序集: <entityFramework codeConfigurationType="Namespace.MyConfiguration,ApplicationAssembly"> ...snipped... </entityFramework> 这样做的副作用是,如果/当您启用迁移时,您需要明确说明您正在使用的上下文.这显然是因为你现在在程序集中有两种上下文类型(除非你将它们拆分出来.)所以你现在需要运行这样的命令: enable-migrations -ContextTypeName Namespace.YourContextClass (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |