Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF ChangeTracker Accessing Tracked Entity and its navigation collection

I would like to track changes. I have a class/model

public class Emp
{ 
    public MoreInfo MoreInfo { get; set; }  
    public ICollection<Works> Works { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
}


foreach (var e in _db.ChangeTracker.Entries<TEntity>())
{
   foreach (var key in e.Properties)
   {  
         if (key.IsModified)
         {
          //I can get the FirstName, LastName fields
         }
   }
}

But I cant figure out how do I loop MoreInfo and ICollection Works and check its parameters ?

like image 898
Ben Avatar asked Oct 20 '25 16:10

Ben


1 Answers

By EF Core terminology these are not properties, but navigations, so they cannot be accessed through Properties. Use Navigations property to get entries (with common properties/methods) for both reference and collection navigation properties

foreach (var navEntry in e.Navigations)
{
    // e.MoreInfo, e.Works
    if (navEntry.IsModified)
    {
    }
}

or Reference and Collections to get the respective entries (with specific properties/methods)

foreach (var refEntry in e.References)
{
    // e.MoreInfo
    if (refEntry.IsModified)
    {
    }
}
foreach (var colEntry in e.Collections)
{
    // e.Works
    if (colEntry.IsModified)
    {
    }
}

But both properties and navigations are considered to be members, so you can use Members to process them all using the common properties/methods

foreach (var memberEntry in e.Members)
{
    // e.MoreInfo, e.Works, e.FirstName, e.LastName
    if (memberEntry.IsModified)
    {
    }
}
like image 51
Ivan Stoev Avatar answered Oct 27 '25 08:10

Ivan Stoev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!