title: Using Entity Framework to insert row to a table that has a composite key
body: <p>I am inserting a new row to the database table using Entity Framework, but my problem is that column <code>ValidFromDate</code> is causing an exception </p>
  
  <blockquote>
    <p>The property 'ValidFromDate' is part of the object's key information
    and cannot be modified date</p>
  </blockquote>
  
  <p>Our DBA has defined database and image below is the snapshot of the EDMX file. <code>ValidFromDate</code> is a <em>datetime</em> column.</p>
  
  <p>Idea of the <code>FarmAnimal</code> is to track the history of where certain animal has been. Therefore <code>AnimalId</code> <strong>and</strong> <code>ValidFromDate</code> causes the row to be unique.</p>
  
  <p>Now the question is that how can I can insert new row to the table that has this kind of schema?</p>
  
  <p><img src="https://i.stack.imgur.com/pC4Nz.png" alt="EDMX"></p>
  
  <p>Insert using Entity Framework</p>
  
  <pre><code>var farmAnimal = new FarmAnimal {
     AnimalId = insert.AnimalId,
     ValidFromDate = insert.ValidFromDate // exception comes from this line,
     etc.
  };
  entities.FarmAnimals.Add(farmAnimal);
  </code></pre>
  
  <p><strong>Update: StackTrace</strong></p>
  
  <pre><code>   at System.Data.Objects.EntityEntry.DetectChangesInProperties(Boolean detectOnlyComplexProperties)
     at System.Data.Objects.ObjectStateManager.DetectChangesInScalarAndComplexProperties(IList`1 entries)
     at System.Data.Objects.ObjectStateManager.DetectChanges()
     at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
     at System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
     at System.Data.Entity.DbSet`1.Add(TEntity entity)
     at xxx.Repositories.PairingRepository.UpdateFarmAnimals(IEnumerable`1 updates, IEnumerable`1 inserts) in xxx
     at xxx.Services.PairingService.RemovePairingAnimals(List`1 animalIds) in xxx
     at xxx.Controllers.PairingController.RemovePairingAnimals(List`1 animalIds) in xxx
     at lambda_method(Closure , ControllerBase , Object[] )
     at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
     at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
     at System.Web.Mvc.ControllerActionInvoker.&lt;&gt;c__DisplayClass15.&lt;InvokeActionMethodWithFilters&gt;b__12()
     at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
  </code></pre>
  
  <p><strong>Update 2: Entity Framework files</strong></p>
  
  <p>I have added three files Entity Framework mapping files / generators 
  EDMX file
  ADO.NET DbContext Generator 
  ADO.NET EntityObject Generator (POCO's)</p>