简体   繁体   中英

How to update related entity also when updating one with Attach in EF5?

I have a table Players who have N PlayerAliases (1-N) in database.

When I'm editing player information, I want to update some Players table fields AND update PlayerAliases table fields.

I won't add/delete fields in PlayerAliases, just update. How can I do that in EF?

Code below, from ViewModel and Save function examples. Players model should be similar to ViewModel example..

public class PlayerViewModel
{
    public int PlayerID {get;set;}
    public string Name {get;set;}
    public string Address {get;set;}
    public IEnumerable<Alias> ListAliases {get;set;}
}


public bool UpdatePlayer(PlayerViewModel vm){
    var e = new Players { PlayerID = vm.PlayerID };
    db.Players.Attach(e);

    e.Name = vm.Name;
    e.Address = vm.Address;

    if (vm.ListAliases != null)
    {
        // ??????????????
        // How to update ListAliases ??
    }

    return db.SaveChanges() > 0;
}

I found how.
Attaching directly to related table.

if (vm.ListAliases != null)
{
    foreach (var item in vm.ListAliases )
    {
        var eAlias = new PlayerAliases() { CodPlayerAlias = item.CodPlayerAlias };
        db.PlayerAliases.Attach(eAlias);
        eAlias.Column1 = item.Column1;
        eAlias.Column2 = item.Column2;
    }
}

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