문제

I'm writing a first MVVM application in WPF using EF5 with a "Database First" approach. My model in the MVVM is what EF5 has generated for me (I did need to customize the T4 template to include INotifyPropertyChanged).

Everything seems to work fine, changing the text in a textbox raised a propertychanged in my model. I am now trying to save these changes to the database. I get no error, but the changes are not submitted.

I'm afraid that, performing a context.savechanges() in my viewmodel is not enough?

private void UpdatePerson()
    {
        using (CvContext ctx = new CvContext())
        {
            ctx.SaveChanges();
        }
    }

in my XAML I have:

<UserControl.DataContext>
    <myViewModels:PersonDetailViewModel/>
</UserControl.DataContext>
<TextBox Grid.Row="1" Grid.Column="1" x:Name="txtLastName" Text="{Binding Path=Lastname}"></TextBox>

Do I need to define insert/update/delete in the edmx designer or is this not really necessary?

Thanks in advance for your help! Best regards, YK

도움이 되었습니까?

해결책

I have done something similar within my application. Try something Like I have below (I usually use a repository for this so change to suit your needs);

private void UpdatePerson(PersonViewModel v)
{
    using (ProActiveDBEntities context = new ProActiveDBEntities())
    {
        var p = context.Users.Where(c => c.PersonID == v.PersonID).SingleOrDefault(); //retrieve the person by its PK ID

        if (p != null)
        {
           p.PersonID = v.PersonID; //Map the properties/Fields within your EF model to the ones in your view model
           p.Surname = v.Surname;
           //etc...

           context.SaveChanges();
        }
     }
}

Like I said, I usually use a repository to create my CRUD operations for EF. But within the method, I have a parameter of my ViewModel. I then create an expression that matches the ID of the entity table to the ID of the ViewModel. It then updates the corresponding data in which is mapped.

Then, within my ViewModel I do the following - for example;

private Void Update()
{
     PersonRepository rep = new PersonRepository();
     rep.UpdatePerson(this);
}

This is my way of achieving this. There are different ways and different approaches that you can do.

If I have missed something then let me know :). Hope this helped! :)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top