我有以下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; }
}
玩家表中最初的种子数据:
现在我要更新其中一位击球手的name
和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属性:
如何更新子类和父类的属性?
答案 0 :(得分:2)
从这个答案来看,这是解决方法: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并可能会开启一个新问题