简体   繁体   中英

Entity Framework Save changes List<>

I just started working with MVVM. There are also a lot of topics about this. But I can't see the wood for the trees...

It's a basic question (beginner @ EF and MVVM)

I have a List<Klanten> in my ViewModel. You should be able to edit this list. And when the list is edited I want to be able to save the changes to the DB.

Before I used MVVM I would do something like:

_entities.SaveChanges();

But now my data is changed in the list and not in the context self. I want to know how I reflect my changes of the list to the db on a proper way.

I found some answers where they checked every object of the list with the context to check if something has changed or added. But I don't like that solution isn't there another better way? Or should I stick to that solution.

Feel free to post blog's (or other stuff) about it, I'd like to learn more.

Thanks, Brecht

Someone has to do change tracking right? Entity doesn't know about any changes until you tell it what's changed, so you can either give it the entire List and let it Add/Update every one, or you can do the tracking yourself as those 'some answers' have suggested. Really no magical way to do it I'm afraid :(

Thanks guys! So I guess there is no magic trick :)

I solved it by doing this:

    DataEntities ctx = new DataEntities();
    public List<Klant> Klanten
    {
        get { return ctx.Klanten.ToList(); }
    }

    public void AddKlant(Klant k)
    {
        ctx.Klanten.Add(k);
        ctx.SaveChanges();
        Refresh();
    }

    public void Refresh()
    {
        ViewSource.Source = Klanten;
    }

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