c# – 更新Entity Framework 7中的继承实体

我有以下BaseballDbContext类:

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

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

我的模型类是:

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; }
}

玩家表中最初的种子数据:

《c# – 更新Entity Framework 7中的继承实体》

现在我想更新其中一个击球手的名字和homeruns属性:

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();

运行代码后,只有玩家的名字得到更新,而不是homeruns属性:

《c# – 更新Entity Framework 7中的继承实体》

如何更新子类和父类的属性?

最佳答案 从这个答案,但这是一个解决方法:
Save changes to child class properties using 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();
}

我想你应该看看opened issues related to inheritance,可能会开一个新问题

点赞