Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用PetaPOCO(Umbraco 6,MVC)修改现有数据库表(添加/删除列)_C#_Sql_Umbraco_Petapoco_Umbraco6 - Fatal编程技术网

C# 如何使用PetaPOCO(Umbraco 6,MVC)修改现有数据库表(添加/删除列)

C# 如何使用PetaPOCO(Umbraco 6,MVC)修改现有数据库表(添加/删除列),c#,sql,umbraco,petapoco,umbraco6,C#,Sql,Umbraco,Petapoco,Umbraco6,我有一个Umbraco CMS应用程序,带有一些自定义功能,我使用PetaPOCO将数据存储在数据库中。 我创建了我的POCO和一个Umbraco事件,该事件在应用程序启动时触发,以创建不存在的表: public class RegisterEvents : ApplicationEventHandler { //This happens everytime the Umbraco Application starts protected override void Applic

我有一个Umbraco CMS应用程序,带有一些自定义功能,我使用PetaPOCO将数据存储在数据库中。 我创建了我的POCO和一个Umbraco事件,该事件在应用程序启动时触发,以创建不存在的表:

public class RegisterEvents : ApplicationEventHandler
{
    //This happens everytime the Umbraco Application starts
    protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
    {
        //Get the Umbraco Database context
        var db = applicationContext.DatabaseContext.Database;

        //Check if the DB table does NOT exist
        if (!db.TableExist("MyTable"))
        {
            //Create DB table - and set overwrite to false
            db.CreateTable<MyPetaPOCO>(false);
        }
    }
}
公共类注册事件:ApplicationEventHandler
{
//每次启动Umbraco应用程序时都会发生这种情况
受保护的覆盖无效应用程序已启动(UmbracoApplicationBase umbracoApplication、ApplicationContext ApplicationContext)
{
//获取Umbraco数据库上下文
var db=applicationContext.DatabaseContext.Database;
//检查DB表是否不存在
如果(!db.TableExist(“MyTable”))
{
//创建数据库表-并将覆盖设置为false
db.CreateTable(false);
}
}
}
如何在不直接访问数据库的情况下修改现有数据库(我想添加一列)?我需要使用代码,因为主机还没有提供访问权限。我想我应该能够在这个ApplicationStartedOverride事件中做到这一点,但我不知道如何做到

编辑


如果您使用的是PetaPoco,那么可以使用
db.Execute(“alter table…”)
,但是您需要有足够的访问权限来执行这样的DDL语句

我也会在PetaPoco事务中运行它,因为这是一个很好的实践


最后,如果您在应用程序启动时运行此操作(这很好),则需要执行检查以确保该列不存在。

如果这是一个包或您正在部署(或让其他人使用)的内容,则应创建一个迁移,并在ApplicationStarted方法中运行它

上述文章中的示例:

要向现有PetaPOCO数据库添加列,请执行以下操作:

创建从MigrationBase派生的迁移类:

[Migration("1.0.1", 1, "YourTableName")]
  public class AddNewColumnToTable : MigrationBase
  {
    public AddNewColumnToTable(ISqlSyntaxProvider sqlSyntax, ILogger logger) 
      : base(sqlSyntax, logger)
    { }

    public override void Up()
    {
      Alter.Table("YourTableName").AddColumn("ColumnToAdd").AsString().Nullable();
    }

    public override void Down()
    {
      Delete.Column("ColumnToAdd").FromTable("YourTableName");
    }
  }
  public class MyApplication : ApplicationEventHandler
  {
    protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
    {
      HandleStatisticsMigration();
    }

    private static void HandleStatisticsMigration()
    {
      const string productName = "YourTableName";
      var currentVersion = new SemVersion(0, 0, 0);

      // get all migrations for "YourTableName" already executed
      var migrations = ApplicationContext.Current.Services.MigrationEntryService.GetAll(productName);

     // get the latest migration for "YourTableName" executed
     var latestMigration = migrations.OrderByDescending(x => x.Version).FirstOrDefault();

     if (latestMigration != null)
       currentVersion = latestMigration.Version;

     var targetVersion = new SemVersion(1, 0, 1);
     if (targetVersion == currentVersion)
       return;

     var migrationsRunner = new MigrationRunner(
       ApplicationContext.Current.Services.MigrationEntryService,
       ApplicationContext.Current.ProfilingLogger.Logger,
       currentVersion,
       targetVersion,
       productName);

     try
     {
       migrationsRunner.Execute(UmbracoContext.Current.Application.DatabaseContext.Database);
     }
     catch (Exception e)
     {
       LogHelper.Error<MyApplication>("Error running YourTableName migration", e);
     }
   }
 }
使用运行迁移的逻辑更新启动的
应用程序:

[Migration("1.0.1", 1, "YourTableName")]
  public class AddNewColumnToTable : MigrationBase
  {
    public AddNewColumnToTable(ISqlSyntaxProvider sqlSyntax, ILogger logger) 
      : base(sqlSyntax, logger)
    { }

    public override void Up()
    {
      Alter.Table("YourTableName").AddColumn("ColumnToAdd").AsString().Nullable();
    }

    public override void Down()
    {
      Delete.Column("ColumnToAdd").FromTable("YourTableName");
    }
  }
  public class MyApplication : ApplicationEventHandler
  {
    protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
    {
      HandleStatisticsMigration();
    }

    private static void HandleStatisticsMigration()
    {
      const string productName = "YourTableName";
      var currentVersion = new SemVersion(0, 0, 0);

      // get all migrations for "YourTableName" already executed
      var migrations = ApplicationContext.Current.Services.MigrationEntryService.GetAll(productName);

     // get the latest migration for "YourTableName" executed
     var latestMigration = migrations.OrderByDescending(x => x.Version).FirstOrDefault();

     if (latestMigration != null)
       currentVersion = latestMigration.Version;

     var targetVersion = new SemVersion(1, 0, 1);
     if (targetVersion == currentVersion)
       return;

     var migrationsRunner = new MigrationRunner(
       ApplicationContext.Current.Services.MigrationEntryService,
       ApplicationContext.Current.ProfilingLogger.Logger,
       currentVersion,
       targetVersion,
       productName);

     try
     {
       migrationsRunner.Execute(UmbracoContext.Current.Application.DatabaseContext.Database);
     }
     catch (Exception e)
     {
       LogHelper.Error<MyApplication>("Error running YourTableName migration", e);
     }
   }
 }
公共类MyApplication:ApplicationEventHandler
{
受保护的覆盖无效应用程序已启动(UmbracoApplicationBase umbracoApplication、ApplicationContext ApplicationContext)
{
手统计学迁移();
}
私有静态void HandleStatisticsMigration()
{
常量字符串productName=“YourTableName”;
var currentVersion=新版本(0,0,0);
//获取已执行的“YourTableName”的所有迁移
var migrations=ApplicationContext.Current.Services.MigrationEntryService.GetAll(productName);
//获取执行的“YourTableName”的最新迁移
var latestMigration=migrations.OrderByDescending(x=>x.Version).FirstOrDefault();
if(latestMigration!=null)
currentVersion=最新迁移。版本;
var targetVersion=新版本(1,0,1);
如果(targetVersion==currentVersion)
返回;
var MigrationRunner=新的MigrationRunner(
ApplicationContext.Current.Services.MigrationEntryService,
ApplicationContext.Current.ProfilingLogger.Logger,
当前版本,
目标版本,
产品名称);
尝试
{
MigrationRunner.Execute(UmbracoContext.Current.Application.DatabaseContext.Database);
}
捕获(例外e)
{
LogHelper.Error(“运行表名迁移时出错”,e);
}
}
}
请注意,目标版本应与您在
迁移
类属性中设置的版本相匹配(在本例中为1.0.1)


当您进行更新并向应用程序或插件添加新功能时,您将创建新的迁移(如果需要),并更新目标版本

Digby,哇,这个执行方法在PetaPOCO文档中隐藏得非常好(在其他有更多文档的文档之间只有几行)。谢谢,我将尝试您的解决方案。请为这一杯喝一杯你自己酿造的;),干杯