public class Person
{
public int Id { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public DateTime DOB { get; set; }
public Person()
{
Id = 0;
LastName = String.Empty;
FirstName = String.Empty;
DOB = DateTime.Now;
}
}
private void button1_Click(object sender, EventArgs e)
{
var v = new Person(){
LastName = "LLLLL";
FirstName = "FFFFF";
DOB = DateTime.Now;
};
_dbContext.Add(v);
// now let's say that the user changes the v.LastName to ...
v.LastName = "QQQQQQQQQQQQQQQQQQQQQQQQQQ";
/* now I would expect _dbContext to be already aware of changes
made to the v.LastName property or at least to have passed the initial
values of the v entity to the OriginalValues of the added entry
and EFCore to providing me with a method to informing me,
whenever I asked so,
if some property values in the entity, being tracked, have been changed!!
*/
//so whenever I type
var changesMadeSoFar = HelloLovelyEFCore_DoWeHaveAnyChangesToThePropertiesOfThisLovelyEntryMadeSoFar(EntityEntry v);
// Unfortunatelly I can't find a way to be inormed of any changes in the properties
// of the entry being tracked!! Unless I am missing something... (which is very possible)
// Even the following fails to provide me information of property changes
made to a NEWLY created entity NOT a loaded for the DB ones.....
EntityEntry<TFlatVisit> entry = _dbContext.Entry(v);
entry.DetectChanges();
var modified = entry.Members.Where(m => m.IsModified).ToList();
var modified2 = entry.Properties.Where(m => m.CurrentValue != m.OriginalValue).ToList();
var modified3 = entry.Properties.Where(m => m.CurrentValue == m.OriginalValue).ToList();
var modified4 = entry.Properties
.Where(prop => prop.IsModified)
.Select(prop => new
{
Property = prop.Metadata,
Value = prop.CurrentValue,
Name = prop.Metadata.Name,
PrevValue = prop.OriginalValue
}).ToList();
if (_dbContext.ChangeTracker.HasChanges())
{
_dbContext.ChangeTracker.DetectChanges();
Debug.WriteLine(_dbContext.ChangeTracker.DebugView.LongView);
}// the latter results into _dbContext has changed and the state of entry v is set to Added (we all know that)
}
PS:我不是要求獲取條目是否已更改!入口狀態更改為已添加。我們都知道!!我特別要求一種方法來了解某些或任何條目的屬性是否已更改。我想通過 EFCore 獲取這些資訊!!不是通過 INotifyPropertyChanged 之類的。希望已經讓你清楚我在追求什么...
PS2:我不是要求對使用 _dbContext 從資料庫加載的物體進行更改。我特別要求提供有關對新創建條目的屬性所做的更改的資訊。
_dbContext 和 EFCore 似乎沒有將新創建的條目屬性的初始值傳遞給 OriginalValues!我不知道為什么會這樣?!?將新創建的條目的 OriginalValues 設定為添加到 _dbContext 的物件的初始值不是很合理嗎?!?所以讓我們有機會通過將原始值與當前值進行比較來檢測屬性的變化?!?!
感謝您的時間
uj5u.com熱心網友回復:
我想不通為什么會這樣?
ChangeTracker 的作業是確定運行什么 DML 陳述句以將物體與資料庫同步。跟蹤對已添加所做的更改對于實作此目標不是必需的,并且具有非零性能成本。
如果您愿意,如果您希望 EF 跟蹤更改,您可以附加物體,然后在 SaveChanges 之前將狀態更改為已添加。但是更改跟蹤物體必須有一個鍵集,因此如果鍵是資料庫生成的,則必須將其設定為非零值,如果將狀態更改為已添加,則將其重置為 0。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/527929.html
