title: How to cast base class to derived class using Entity Framework
body: <p>I'm trying to cast base object to derived class object using Entity Framework.  </p>
  
  <p>I tried to use the copy constructor. The constructor itself does work, but the framework throw errors.</p>
  
  <p>Model classes:</p>
  
  <pre><code>public class Member
  {
      [Key]
      public string SRU { get; set; }
      public string Name { get; set; }
      public string Email { get; set; }
      public virtual Address Address { get; set; }
  
  }
  
  public class Player : Member
  {
      public virtual PlayerPosition Position { get; set; }
      public virtual Doctor Doctor { get; set; }
      public virtual HealthIssue HealthIssue { get; set; }
  
      public Player()
      {
  
      }
      public Player(Member m)
      {
          SRU = m.SRU;
          Name = m.Name;
          Email = m.Email;
          Address = m.Address;
      }
  }
  </code></pre>
  
  <p>My attempt:</p>
  
  <pre><code>DatabaseModel db = new DatabaseModel();
  
  var val = db.Members
              .FirstOrDefault(b =&gt; b.Name == "Frank");
  
  val = new Player(val);
  db.Members.Update(val);
  
  // Save changes in database
  db.SaveChanges();
  </code></pre>
  
  <p>I expected to update this entity but it throws error:</p>
  
  <blockquote>
    <p>System.InvalidOperationException: 
    'The instance of entity type 'Player' cannot be tracked because another instance with the same key value for {'SRU'} is already being tracked. </p>
    
    <p>When attaching existing entities, ensure that only one entity instance with a given key value is attached. </p>
  </blockquote>
  
  <p>Edit:</p>
  
  <p>I tried it but I change name but type is still same.</p>
  
  <pre><code>DatabaseModel db = new DatabaseModel();
  
  var val = db.Members
              .FirstOrDefault(b =&gt; b.Name == "Yordan");
  db.Entry(val).State = EntityState.Detached;
  
  var val2 = new Player(val);
  val2.Name = "Frank";
  
  db.Members.Update(val2);
  db.SaveChanges();
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/Ge4A6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ge4A6.png" alt="Sample data"></a></p>
  
  <p>So i got Member and Player extend Member. In that case I want to cast Member to Player.</p>