使用Umbraco.Core.Persistence从带有枚举的模型创建数据库表

Mat*_*att 4 c# umbraco umbraco7

要在应用程序启动时创建此表(如果不存在)。

码:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

模型:

[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; }
}
Run Code Online (Sandbox Code Playgroud)

错误信息:

[InvalidOperationException:序列不包含匹配的元素] System.Linq.Enumerable.First(IEnumerable 1 source, Func2谓词)+415 Umbraco.Core.Persistence.SqlSyntax.SqlSyntaxProviderBase 1.FormatType(ColumnDefinition column) +1225 Umbraco.Core.Persistence.SqlSyntax.SqlSyntaxProviderBase1.Format(ColumnDefinition列)+155 Umbraco.Core.Persistence.SqlSyntax.SqlSyntaxProviderBase 1.Format(IEnumerable1列)+144 Umbraco.Core.Persistence.SqlSyntax.SqlSyntaxProviderBase`1.Format(TableDefinition table)+131 Umbraco.Core.Persistence.PetaPocoExtensions.CreateTable(数据库db,布尔覆盖,类型为ModelType)+161 Umbraco.Core.Persistence .PetaPocoExtensions.CreateTable(数据库db,布尔覆盖)+121

看着错误,我认为不更新内核就不会有解决方案,但这是希望你们能提供帮助

Har*_*vey 5

在研究@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;
    }
}
Run Code Online (Sandbox Code Playgroud)

在代码中,Type应该使用而不是_type为了使枚举受益。_type仅作为插入数据库表中的字段出现。