我刚开始在 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。另外,当我注释掉“Initialize Indexes”注释后的两行时,一切运行正常(除了你可以保存非唯一键,这是一个问题)~
提交代码(以防我在这部分也做错了什么:)
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();
}
}
请帮忙?提前致谢~
最佳答案
我忘记了 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"));
现在一切正常~ ^^
关于c# - EmbeddedConfiguration 中的 UniqueConstraint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2535086/