简体   繁体   English

实体框架保存更改列表<>

[英]Entity Framework Save changes List<>

I just started working with MVVM. 我刚刚开始使用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) 这是一个基本问题(初学者@ EF和MVVM)

I have a List<Klanten> in my ViewModel. 我的ViewModel中有一个List<Klanten> 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: 在使用MVVM之前,我将执行以下操作:

_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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM