如果这个表不存在,想在应用程序启动时创建它。
代码:
public class Database : ApplicationEventHandler
{
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
var db = applicationContext.DatabaseContext.Database;
//Cant add this table due to the ENUM
if (!db.TableExist("FormData"))
{
db.CreateTable<FormData>(false);
}
}
}
型号:
[PrimaryKey("Id")]
public class FormData
{
[PrimaryKeyColumn(AutoIncrement = true, IdentitySeed = 1)]
public int Id { get; set; }
[NullSetting(NullSetting = NullSettings.NotNull)]
public FormType Type { get; set; }
[NullSetting(NullSetting = NullSettings.NotNull)]
public string Data { get; set; }
[NullSetting(NullSetting = NullSettings.NotNull)]
public DateTime Date { get; set; }
}
错误信息:
[InvalidOperationException: Sequence contains no matching element] System.Linq.Enumerable.First(IEnumerable
1 source, Func
2 predicate) +415 Umbraco.Core.Persistence.SqlSyntax.SqlSyntaxProviderBase1.FormatType(ColumnDefinition column) +1225 Umbraco.Core.Persistence.SqlSyntax.SqlSyntaxProviderBase
1.Format(ColumnDefinition column) +155 Umbraco.Core.Persistence.SqlSyntax.SqlSyntaxProviderBase1.Format(IEnumerable
1 columns) +144 Umbraco.Core.Persistence.SqlSyntax.SqlSyntaxProviderBase`1.Format(TableDefinition table) +131 Umbraco.Core.Persistence.PetaPocoExtensions.CreateTable(Database db, Boolean overwrite, Type modelType) +161 Umbraco.Core.Persistence.PetaPocoExtensions.CreateTable(Database db, Boolean overwrite) +121
查看错误我认为没有更新核心的解决方案但是希望你们能提供帮助
最佳答案
根据@Ryios 给出的答案,我认为这样的事情很好:
/// <summary>
/// Don't use this to get or set.
/// This must however be kept as public or db.CreateTable()
/// will not insert this field into the database.
/// </summary>
[NullSetting(NullSetting = NullSettings.NotNull)]
[Column("type")]
public int _type { get; set; }
/// <summary>
/// This field is ignored by db.CreateTable().
/// </summary>
[Ignore]
public FormType Type
{
get
{
return (FormType)_type;
}
set
{
_type = (int)value;
}
}
在代码中,应该使用 Type
而不是 _type
以便枚举可以从中受益。 _type
仅作为插入数据库表的字段出现。
关于c# - 使用 Umbraco.Core.Persistence 从带有枚举的模型创建数据库表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28633162/