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:我不是在询问条目是否已更改!!条目状态更改为Added。我们都知道这一点!!我是在特别询问一种方法来了解条目的某些或任何属性是否已更改。而且我希望通过EFCore获取此信息!!而不是通过INotifyPropertyChanged之类的东西。希望已经向您说明了我的目的...
PS2:我不是在询问对使用_dbContext从数据库加载的实体所做的更改。我特别询问对新创建条目的属性所做的更改的信息。
看起来_dbContext和EFCore没有将新创建条目的属性的初始值传递给OriginalValues!!我不知道为什么会这样?!?将新创建条目的OriginalValues设置为添加到_dbContext的对象的初始值难道不合理吗?!?因此,让我们有机会通过比较原始值和当前值来检测属性的更改?!?!
谢谢你的时间
1条答案
按热度按时间a1o7rhls1#
我想不出为什么会这样?
ChangeTracker的工作是决定要执行哪一个DML叙述句来同步化实体与数据库。追踪对Added所做的变更并非达成此目的的必要条件,而且会有非零的效能成本。
如果需要,可以这样做。如果希望EF跟踪更改,请附加实体,然后在保存更改之前将状态更改为“已添加”。但是,跟踪更改的实体必须具有键集,因此,如果键是数据库生成的,则必须将其设置为非零值,如果将状态更改为“已添加”,则将其重置为0。