简体   繁体   中英

Update inherited Entity in Entity Framework 7

I have the following BaseballDbContext class:

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 are:

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 players table:

在此输入图像描述

Now I want to update name and homeruns property of one of the hitters:

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 I run the code only player's name got update, but not the homeruns property:

在此输入图像描述

How to update property of both child and parent class ?

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

Do Not track changes using 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();
}

I think you should have a look at the opened issues related to inheritance and may be open a new issue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM