Brian Ogden Brian Ogden - 1 year ago 76
C# Question

Surprised that Entity Framework is saving a detached Entity correctly

I have an entity class

, I get this entity from this method:

public Timecard GetTimeCardForPerson(long timecardId)
return timecardContext.First(item => item.TimeCardId = timeCardId);

timecardContext is of type
TimecardContext: DbContext

I later make a change to the
entity, the
entity has a property:

public virtual ICollection<TimecardRow> TimeCardRows { get; set; }

which is initialized, in
constructor to a
like so:

this.TimeCardRows = new HashSet<TimecardRow>();

I add a child
I then call another method and this is its exact implementation and pass it the same Timecard instance as is returned from

public void SaveTimecard(Timecard timeCard)
timecardContext.Entry(timeCard).State = timeCard.TimecardId == 0
? EntityState.Added
: EntityState.Unchanged;


The passed in
Timecard timeCard
argument is not attached to the
and has a TimecardId > 0.

I am surprised that my new
saves successfully as Entry(timeCard.State) is set to

The EntityState.Unchanged tells my timecardContext that there is nothing to change, does it not? But all the same, the
I added is inserted into the database when the
method is called.

Answer Source

The EntityState.Unchanged tells the context that nothing has changed for the Timecard entity.

The TimecardRow is a separate entity which EF will track separately so a call to SaveChanges will insert that entity.

The above assumes that the Timecard is already attached when passed to the Save method (which it will be if it's the same instance returned from the GetTimeCardForPerson method).

If the Id check in the Save method is there to cope with both detached and attached entities, would it be better to leave the state alone unless it is an id of 0?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download