Update Legacy Entity in Entity Framework 7

I have the following class BaseballDbContext:

public class BaseballDbContext : DbContext
{
   public DbSet<BaseballTeam> teams { get; set; }

   protected override void OnModelCreating(ModelBuilder modelBuilder)
   {
       modelBuilder.Entity<Hitter>();
       modelBuilder.Entity<Pitcher>();
   }
}

And my model classes:

public class BaseballTeam
{
    public int Id { get; set; }
    public string teamName { get; set; }
    public List<BaseballPlayer> players { get; set; }
}

public abstract class BaseballPlayer
{
    public int Id { get; set; }
    public int age { get; set; }
    public string name { get; set; }
}

public class Hitter : BaseballPlayer
{
    public int homeruns { get; set; }
}

public class Pitcher : BaseballPlayer
{
    public int strikeouts { get; set; }
}

Initially seeded data in the table of players:

enter image description here

Now I want to upgrade the property nameand homerunsone of the attackers:

BaseballTeam team = _ctx.teams.Include(q => q.players).FirstOrDefault();
Hitter hitter = team.players.OfType<Hitter>().FirstOrDefault();
hitter.name = "Tulowitzki";  //that property will be updated
hitter.homeruns = 399;       //but that will not :(

int i = team.players.FindIndex(q => q.Id == hitter.Id);
team.players[i] = hitter;

_ctx.Update(team);
_ctx.SaveChanges();

After running the code, only the player name received the update, but not the homeruns property:

enter image description here

How to update property of both child and parent classes?

+4
source share
1 answer

From this answer, but this is a workaround : Save changes to the properties of the child class using a base class query with Entity Framework TPH patten :

AsNoTracking()

using (var context = new BaseballDbContext())
{
    var team = context.teams.Include(q => q.players).AsNoTracking().FirstOrDefault();
    var hitter = team.players.OfType<Hitter>().FirstOrDefault();
    hitter.name = "Donaldson";
    hitter.homeruns = 999;
    context.Update(team);
    context.SaveChanges();
}

, , ,

+2

All Articles