Brian Ogden Brian Ogden - 20 days ago 5
C# Question

Surprised that Entity Framework is saving a detached Entity correctly

I have an entity class

Timecard
, 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
Timecard
entity, the
Timecard
entity has a property:

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


which is initialized, in
Timecard's
constructor to a
HashSet
like so:

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


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

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


timecardContext.SaveChanges();
}


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

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

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

Answer

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?