EmbeddedConfiguration中的UniqueConstraint

时间:2010-03-28 23:53:52

标签: c# db4o

我刚开始在C#上使用db4o,而我在数据库上设置UniqueConstraint时遇到了麻烦..

这是db4o配置

static IObjectContainer db = Db4oEmbedded.OpenFile(dbase.Configuration(), "data.db4o");
static IEmbeddedConfiguration Configuration()
{
    IEmbeddedConfiguration dbConfig = Db4oEmbedded.NewConfiguration();
    // Initialize Replication
    dbConfig.File.GenerateUUIDs = ConfigScope.Globally;
    dbConfig.File.GenerateVersionNumbers = ConfigScope.Globally;
    // Initialize Indexes
    dbConfig.Common.ObjectClass(typeof(DAObs.Environment)).ObjectField("Key").Indexed(true);
    dbConfig.Common.Add(new Db4objects.Db4o.Constraints.UniqueFieldValueConstraint(typeof(DAObs.Environment), "Key"));
    return dbConfig;
}

和要序列化的对象:

class Environment
{
    public string Key { get; set; }
    public string Value { get; set; }
}

每次我提交一些值时,“对象引用未设置为对象的实例”。弹出异常,堆栈跟踪指向UniqueFieldValueConstraint。此外,当我在“初始化索引”注释后注释掉两行时,一切运行正常(除非您可以保存非唯一键,这是一个问题)〜

提交代码(如果我在这部分也做错了一些事情:)

public static void Create(string key, string value)
{
    try
    {
        db.Store(new DAObs.Environment() { Key = key, Value = value });
        db.Commit();
    }
    catch (Db4objects.Db4o.Events.EventException ex)
    {
        System.Console.WriteLine
            (DateTime.Now +  " :: Environment.Create\n" + ex.InnerException.Message +"\n" + ex.InnerException.StackTrace);
        db.Rollback();
    }
}

请帮忙吗?提前谢谢〜

1 个答案:

答案 0 :(得分:2)

我忘了C#使用奇怪的后备字段作为属性快捷方式:(将配置更新为以下内容:

// Initialize Indexes
dbConfig.Common.ObjectClass(typeof(DAObs.Environment))
    .ObjectField("<Key>k__BackingField").Indexed(true);
dbConfig.Common.Add(new Db4objects.Db4o.Constraints.
    UniqueFieldValueConstraint(typeof(DAObs.Environment), "<Key>k__BackingField"));

现在一切正常〜^^