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

标签 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);
        }
    }
}

型号:

[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(IEnumerable1 source, Func2 predicate) +415 Umbraco.Core.Persistence.SqlSyntax.SqlSyntaxProviderBase1.FormatType(ColumnDefinition column) +1225 Umbraco.Core.Persistence.SqlSyntax.SqlSyntaxProviderBase1.Format(ColumnDefinition column) +155 Umbraco.Core.Persistence.SqlSyntax.SqlSyntaxProviderBase1.Format(IEnumerable1 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/

相关文章:

c# - '&'在xml中怎么写?

umbraco - ApplicationEventHandler 中的依赖注入(inject)。漏洞?

c# - 隐藏 Umbraco 属性

c# - 如何修复异常无法加载 DLL 'gdiplus.dll' : The specified module could not be found

c# - 使用 TFS SDK 查询源代码管理权限时的性能问题

razor - Umbraco 7.2.0 - 使用 Razor 中的 where 子句获取节点的后代

Umbraco: "System.InvalidOperationException: The view found at ' ~/Views/Homepage.cshtml' 未创建。”

mysql - 提交时点击在 umbraco 中出现问题

c# - 微软图表 Winforms。如何去除空白点?

Umbraco 覆盖或扩展默认成员资格提供者