我有点苦恼,我将在这里描述它。我有一个 foreach 循环,我在表中插入行。但在插入之前,我想检查我是否已经有一行具有相同的 ID,如果是,其他属性(列)是否具有相同的值。
这就是我所做的:
var sourceList = LoadFromOtherDataBase();
var res = ListAll(); // Load all rows from database which were already inserted...
foreach (Whatever w in sourceList)
{
Entry entry = new Entry();
entry.id = w.id;
entry.field1 = w.firstfield;
entry.field2 = w.secondfield;
//so on...
//Now, check if this entry was already inserted into the table...
var check = res.Where(n => n.id == entry.id);
if (check.Count() > 0)
{
var alreadyInserted = res.Single(n => n.id == entry.id);
//Here, I need to see if 'alreadyInserted' has the same properties as 'entry' and act upon it. If same properties, do nothing, otherwise, update alreadyInserted with entry's values.
}
else
{
//Then I'll insert it as a new row obviously....
}
}
我想到了 Object.Equals() 但 Entity Framework 为alreadyInserted创建了一个非 null EntityKey属性,该属性在entry中设置为 null 。我认为这就是为什么它不起作用。EntityKey不能设置为 null。
关于如何做到这一点的任何想法,而不必手动检查所有属性(在我的情况下实际上是 25+)?