0
我在一個小菜一碟,我將在這裏描述它。我有一個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(),但實體框架創建一個非空的EntityKey屬性alreadyInserted,其設置爲null在條目。我認爲這是爲什麼它不起作用。 EntityKey不能設置爲空。
任何想法如何做到這一點,而無需手動檢查所有屬性(實際上是25+)?
是的,優秀的。不知道爲什麼我沒有想到它。在if檢查值之前添加了這個:if(propertyInfo.Name!=「EntityState」&& propertyInfo.Name!=「EntityKey」),因爲這些不需要檢查。 –