我有以下BaseballDbContext
類:更新繼承實體,實體框架7
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();
後,我運行的代碼只有玩家的名字得到了更新,但不是本壘打屬性:兩個孩子的
如何更新屬性和父類?
你不需要'DbSet'嗎?見[這裏](http://weblogs.asp.net/manavi/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-1-table-per-hierarchy-tph) –
不,我不需要它。這是一個抽象類。 – koryakinp
這可能值得一試:'_ctx.Entry(team).State = EntityState.Modified'把它放在更新調用之前。 – Cicero