这是一个更通用的解决方案,可以基于@Artjom 和@PiotrSzmyd 的解决方案进入您的migration.cs 文件。该解决方案处理了自动生成的主键可能为模块的每个用户命名不同的事实。如果用户定义了全局数据库前缀(例如,当使用多租户时),表名也可以作为前缀。
// Manually add the column that is required for the part to be a ContentPartVersionRecord
SchemaBuilder.AlterTable("MyCustomPartRecord", table => table.AddColumn<int>("ContentItemRecord_id"));
// Get table name
var tablePrefix = String.IsNullOrEmpty(_shellSettings.DataTablePrefix) ? "" : _shellSettings.DataTablePrefix + "_";
var tableName = tablePrefix + "MyModule_MyCustomPartRecord";
// Drop the primary key
SchemaBuilder.ExecuteSql(string.Format(@"
DECLARE @primaryKeyName NVARCHAR(MAX)
SELECT @primaryKeyName = constraint_name
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_TYPE = 'Primary Key' and TABLE_NAME = '{0}'
EXEC(N'ALTER TABLE {0} DROP CONSTRAINT ' + @primaryKeyName)
", tableName));
// Migrate IDs to ContentItemRecord_id
SchemaBuilder.ExecuteSql(string.Format(@"
INSERT INTO {0} (Id, ContentItemRecord_id, Category_Id, ItemCode, Name, Description, DisplayOrder, Location, MaintenanceFrequency, MaintenanceFrequencyMultiplier, MaintenanceStartDate, Notes, IsEnabled)
SELECT V.Id as Id, T.Id as ContentItemRecord_id, Category_Id, ItemCode, Name, Description, DisplayOrder, Location, MaintenanceFrequency, MaintenanceFrequencyMultiplier, MaintenanceStartDate, Notes, IsEnabled
FROM {0} T
LEFT OUTER JOIN
{1}Orchard_Framework_ContentItemVersionRecord AS V ON V.ID in
(select top(1) Id
from {1}Orchard_Framework_ContentItemVersionRecord
where ContentItemRecord_id = T.ID
order by latest desc, id desc)
", tableName, tablePrefix));
// Remove old rows (no ContentItemRecord_id value)
SchemaBuilder.ExecuteSql(string.Format(@"
DELETE FROM {0}
WHERE ContentItemRecord_id is NULL
", tableName));
// Re-add the primary key
SchemaBuilder.ExecuteSql(string.Format(@"
ALTER TABLE {0}
ADD CONSTRAINT PK_{0}_Id PRIMARY KEY (Id)
", tableName));