Amila Silva
Amila Silva

Reputation: 37

Entity Framework 4.1 Identifying New Entities in the Context

I have a base class like below. All my entities inherit from this

public abstract Entity
{
  public DataTime CreationDate{get;set;}
  public DataTime ModifiedDate{get;set;}
}

I want to set the CreationDate when new entity is added to the database.

By overriding SaveChanges() method and checking EntityState is in Modified state I can set the ModifiedDate.

The problem is I can not identify whether it is a new entity or not by checking the EntityState because new entities and other loaded entities are in Added state.

So is there a way to differentiate new entities?

thanks in advance.

Upvotes: 1

Views: 464

Answers (2)

Stephan Keller
Stephan Keller

Reputation: 1633

I worked around this by going through the items in ChangeTracker.Entries() and assigning the current Date/Time to creation dates where the CreationDate-Property is null. Example:

public override int SaveChanges()
{
  DateTime saveTime = DateTime.Now;
  foreach (var entry in this.ChangeTracker.Entries())
  {
    if (entry.Entity is Entity)
    {
      if (entry.Property("CreationDate").CurrentValue == null)
        entry.Property("CreationDate").CurrentValue = saveTime;
      entry.Property("ModifiedDate").CurrentValue = saveTime;

     }
   }
   return base.SaveChanges();
}

Upvotes: 0

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364259

Loaded entities are always in Unchanged state. Newly added entities in Added state, changed entities in Modified state and removed entities in Deleted state. If you see any other behavior your are doing something wrong or use EF incorrectly. Btw. unless your creation process doesn't take really long time, setting CreationDate can be done simply by:

public Entity()
{
    CreationDate = DateTime.Now;
}

Upvotes: 1

Related Questions