2016-04-07 78 views
4

我有以下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; } 
} 

開始播種數據:

enter image description here

現在我想更新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(); 

後,我運行的代碼只有玩家的名字得到了更新,但不是本壘打屬性:兩個孩子的

enter image description here

如何更新屬性和父類?

+0

你不需要'DbSet '嗎?見[這裏](http://weblogs.asp.net/manavi/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-1-table-per-hierarchy-tph) –

+0

不,我不需要它。這是一個抽象類。 – koryakinp

+0

這可能值得一試:'_ctx.Entry(team).State = EntityState.Modified'把它放在更新調用之前。 – Cicero

回答

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和可能開個新的問題

+0

謝謝先生。我會嘗試,但它看起來很醜.. – koryakinp

+0

當然...這就是爲什麼也許你必須打開一個問題...我認爲,因爲你沒有跟蹤更改,當你執行更新上下文驗證每個屬性在每個對象上,但真的不確定 – Thomas