EFCore:是否可以跟踪对新创建并添加到 DbContext 条目的属性所做的更改?我不要求输入状态。已添加


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)
}

附言:我并不是要求得到条目是否已经更改!!条目状态更改为"已添加"。我们都知道!!我特别想知道条目的某些或任何属性是否发生了更改。我想通过EFCore获得这些信息!!不是通过INotifyPropertyChanged之类的方式。希望我能向你表明我在追求什么。。。

PS2:我不是要求对使用_dbContext从数据库加载的实体进行更改。我特别要求提供有关对新创建条目的属性所做更改的信息。

_dbContext和EFCore似乎没有将新建条目属性的初始值传递给OriginalValues!!我不明白为什么会这样?!?将新创建的条目的OriginalValues设置为添加到_dbContext的对象的初始值不是很合理吗?!?因此,让我们有机会通过比较原始值和当前值来检测属性的变化?!?!

感谢您的时间

我不明白为什么会这样?

ChangeTracker的任务是确定要运行哪个DML语句来将实体与数据库同步。跟踪对Added所做的更改对于实现此目标是不必要的,并且具有非零的性能成本。

如果你愿意,你可以。如果希望EF跟踪更改,请附加实体,然后将状态更改为SaveChanges之前已添加。但是,更改跟踪的实体必须有一个密钥集,因此,如果密钥是数据库生成的,则必须将其设置为非零值,如果将状态更改为"已添加",则必须重置为0。

最新更新