我有一个实体,集国家,反映了我的数据库的数据库表 '<' CHAR(2),焦炭(3),为nvarchar(50>。的EntityFramework,插入如果不存在,否则更新
我有一个解析器,它返回一个解析国家的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脚本插入它们而不是等检查一个国家在插入之前已经在数据库中了?
解决方案
请参阅后的回复。
我加覆盖等于我的祖国类:
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();
}
此外,您可以使用新发布的库,它会自动设置实体图中所有实体的定义。你可以阅读[我对类似问题的回答](http://stackoverflow.com/questions/5557829/update-row-if-it-exists-else-insert-logic-with-entity-framework/39609020#39609020) 。 –