【发布时间】:2012-01-30 16:34:24
【问题描述】:
当我试图将对象列表存储到 ravendb 时,我发现了一个奇怪的错误(在我的代码中)。问题是要存储的对象具有由 resharper 生成的相等成员。有问题的对象如下(注意我已经注释掉了平等成员来解决问题)-
//[DataContract(Namespace = "")]
//[KnownType(typeof(IApplicationEntity))]
public class ApplicationEntity: IApplicationEntity
{
public ApplicationEntity()
{
}
public ApplicationEntity(string processName)
{
ProcessName = processName;
Id = "Processes/" + ProcessName;
}
public ApplicationEntity(string key, string processName)
{
ProcessName = processName;
Key = key;
Id = string.Format("Processes/{0}_{1}", Key, ProcessName);
}
//[DataMember]
public string Id { get; set; }
//[DataMember]
public string Key { get; set; }
//[DataMember]
public string ProcessName { get; set; }
//[DataMember]
public string ProcessDescription { get; set; }
/// <summary>
/// used to generate sequential unique activity ID generation only.
/// </summary>
//[DataMember]
public string ActivityCount { get; set; }
//public bool Equals(ApplicationEntity other)
//{
// if (ReferenceEquals(null, other)) return false;
// if (ReferenceEquals(this, other)) return true;
// return Equals(other.ProcessName, ProcessName);
//}
//public override bool Equals(object obj)
//{
// if (ReferenceEquals(null, obj)) return false;
// if (ReferenceEquals(this, obj)) return true;
// if (obj.GetType() != typeof (ApplicationEntity)) return false;
// return Equals((ApplicationEntity) obj);
//}
//public override int GetHashCode()
//{
// return (ProcessName != null ? ProcessName.GetHashCode() : 0);
//}
}
现在,如果我用相等成员实现存储对象,那么下面的代码会产生奇怪的结果 -
int count = 0;
using (var session = _store.OpenSession(_databaseName))
{
foreach (var applicationEntity in _listOfApplications)
{
var entity = new ApplicationEntity(count.ToString(), applicationEntity.ProcessName);
//ravenRepositoryCachable.Add(entity);
session.Store(entity);
count++;
}
session.SaveChanges();
}
奇怪的行为是我希望 Key 字段会增加到 400,因为列表有 400 个成员,但是存储的前 10 个对象的 Key 是正确的,即 0 到 9。但是第 11 个从 0 开始以此类推。
但如果我将相等成员注释掉(如上面的代码 sn-p),那么这个问题就会消失。
另外,如果我一次添加一个对象而不是批处理,问题就会消失 -
int count = 0;
foreach (var applicationEntity in _listOfApplications)
{
using (var session = _store.OpenSession(_databaseName))
{
var entity = new ApplicationEntity(count.ToString(), applicationEntity.ProcessName);
//ravenRepositoryCachable.Add(entity);
session.Store(entity);
session.SaveChanges();
count++;
}
}
我知道我已经解决了这个问题,但我不明白这里发生了什么以及为什么只影响了关键字段?这是一个未定义的行为,我担心代码应该部署在生产中!显然,不定义相等成员。我需要深入了解它,这是一个错误吗?
【问题讨论】:
标签: ravendb