我有一个实体集合“Countries”,反映了我的数据库表中的“<char(2), char(3), nvarchar(50)>”。
我有一个解析器,返回一个已解析的国家数组Country[],并且在正确更新它方面存在问题。我想要的是:对于不在数据库中的国家,请将它们插入,并对已存在的国家进行更新(如果任何字段不同)。这该怎么做?
void Method(object sender, DocumentLoadedEvent e)
{
var data = e.ParsedData as Country[];
using(var db = new DataContractEntities)
{
//Code missing
}
}
我在想,类似于...for(var c in data.Except(db.Countries)) but it wount work as it compares on wronge fields.
希望有人曾经遇到过这个问题,并能为我提供解决方案。如果我不能轻松地使用Country对象并插入/更新它们的数组,那么我认为使用该框架没有太多好处,因为从表现者的角度来看,编写自定义SQL脚本以插入它们可能更快,而不是在插入之前检查国家是否已存在于数据库中。
解决方法
请参见帖子的回答。
我向我的国家类添加了重写equals方法:
public partial class Country
{
public override bool Equals(object obj)
{
if (obj is Country)
{
var country = obj as Country;
return this.CountryTreeLetter.Equals(country.CountryTreeLetter);
}
return false;
}
public override int GetHashCode()
{
int hash = 13;
hash = hash * 7 + (int)CountryTreeLetter[0];
hash = hash * 7 + (int)CountryTreeLetter[1];
hash = hash * 7 + (int)CountryTreeLetter[2];
return hash;
}
}
然后做了:
var data = e.ParsedData as Country[];
using (var db = new entities())
{
foreach (var item in data.Except(db.Countries))
{
db.AddToCountries(item);
}
db.SaveChanges();
}