C#MVVM CodeFirst - Icommand - Sql DataAccess请帮助!!! [英] C# MVVM CodeFirst - Icommand - Sql DataAccess Help Please!!!

查看:67
本文介绍了C#MVVM CodeFirst - Icommand - Sql DataAccess请帮助!!!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

晚上好,我一直在努力学习MVVM和CodeFirst,但是我遇到了一个问题。我似乎无法将我的头脑保存到SQL。



我的示例代码如下,但基本上我想将一个名称和一个地址保存到我的SQL数据库中。



请注意,我已经在EF生成的表格中添加了3个名称和地址。然后我从我的ViewModel填充listview。问题是将用户放在文本框中的内容保存到sql表中。



我的第一个猜测是使用命令参数,但这只允许一个参数字符串,并且我需要两个。





如果有人能帮我实现这一点,我真的很感激,谢谢。



查看:

Good evening, I have been trying to study MVVM and CodeFirst, however I have come across a snag. I cannot seem to get my head round saving to SQL.

My example code is below, but basically I want to save a Name and an Address to my SQL database.

Please note, I already added 3 names and addresses to the table that is generated by EF. I am then populating a listview from my ViewModel. The problem is saving what the user puts in the textboxes, to the sql table.

My first guess was using command parameter, but that only allows one parameter string, and I need two.


If anyone can help me achieve this, I would really appreciate it, thanks.

View:

<Window x:Class="WPFICommandMVVM.View.Person"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Person" Height="300" Width="300">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="100"></ColumnDefinition>
                <ColumnDefinition Width="*"></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="auto"></RowDefinition>
                <RowDefinition Height="auto"></RowDefinition>
            </Grid.RowDefinitions>
            <Label x:Name="lblName" Content="Name" Grid.Row="0" Grid.Column="0"
                   VerticalAlignment="Top"></Label>
            <TextBox x:Name="txtName" Grid.Row="0" Grid.Column="1" VerticalAlignment="Top"
                     Text="{Binding ElementName=lvPerson, Path=SelectedItem.Name}"></TextBox>
            <Label x:Name="lblAddress" Content="Address" Grid.Row="1" Grid.Column="0"
                   VerticalAlignment="Top"></Label>
            <TextBox x:Name="txtAddress" Grid.Row="1" Grid.Column="1" VerticalAlignment="Top"
                     Text="{Binding ElementName=lvPerson, Path=SelectedItem.Address}"></TextBox>
            <Button x:Name="btnUpdate" Width="100" Height="20" VerticalAlignment="Bottom" HorizontalAlignment="Center" Grid.Row="1"
                    Content="Update" Command="{Binding Path=UpdateCommand}" CommandParameter="{Binding
                    ElementName=lvPerson, Path=SelectedItem.Address}" Margin="0,0,0,-60.8"/>
            <ListView x:Name="lvPerson" Grid.Row="1" ItemsSource="{Binding Persons}" Grid.ColumnSpan="2" Margin="0,35.4,99.6,-35.8">
                <ListView.View>
                    <GridView>
                        <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"></GridViewColumn>
                        <GridViewColumn Header="Address" Width="200" DisplayMemberBinding="{Binding Address}"></GridViewColumn>
                    </GridView>
                </ListView.View>
            </ListView>
        </Grid>
    </Grid>
</Window>





型号:



Model:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace WPFICommandMVVM.Model
{
    public class Person : INotifyPropertyChanged
    {
        private int id;
        private string name;
        private string address;


        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged(string propertyName)
        {
            if(PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        public int Id
        {
            get
            {
                return id;
            }
            set
            {
                id = value;
                OnPropertyChanged("Id");
            }
        }

        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
                OnPropertyChanged("Name");
            }
        }

        public string Address
        {
            get
            {
                return address;
            }
            set
            {
                address = value;
                OnPropertyChanged("Address");
            }
        }
    }
}





ViewModel:



ViewModel:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using WPFICommandMVVM.Model;
using WPFICommandMVVM.DataAccess;
using System.Collections.ObjectModel;

namespace WPFICommandMVVM.ViewModel
{
    public class PersonViewModel
    {
        public IList<Person> _personList;
        public IList<Person> PersonList;
        ObservableCollection<Person> obVinyl = new ObservableCollection<Person>();
        public PersonViewModel()
        {
            using (var db = new PersonContext())
            {

                // Display all vinyl from the database

                var query = from b in db.People

                            orderby b.Id

                            select b;


                foreach (var item in query)
                {
                    obVinyl.Add(item);
                    PersonList = obVinyl;
                }
                db.SaveChanges();
            }
            _personList = PersonList;
        }

        public IList<Person> Persons
        {
            get { return _personList; }
            set { _personList = value;}
        }
        private ICommand mUpdater;
        public ICommand UpdateCommand
        {
            get
            {
                if (mUpdater == null)
                    mUpdater = new Updater();
                return mUpdater;
            }
            set
            {
                mUpdater = value;
            }
        }
    }
    class Updater : ICommand
    {
        #region ICommand Members
        public bool CanExecute(object parameter)
        {
            return true;
        }
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public void Execute(object paramenter)
        {
            //InsertPerson method is called here.
            InsertPerson();
            
        }
        #endregion

        private static void InsertPerson()
        {
            var person = new Person
            {

            };

            using (var context = new PersonContext())
            {
                context.People.Add(person);
                context.SaveChanges();
            }
        }
    }
}





DataAccess:



DataAccess:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using WPFICommandMVVM.Model;

namespace WPFICommandMVVM.DataAccess
{
    public class PersonContext : DbContext
    {
       public DbSet<Person> People { get; set; }
    }
}





App.xaml(我在哪里设置datacontext):



App.xaml (Where I set the datacontext):

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using WPFICommandMVVM.ViewModel;

namespace WPFICommandMVVM
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            View.Person person = new View.Person();
            PersonViewModel personViewModel = new PersonViewModel();
            person.DataContext = personViewModel;
            person.Show();
        }
    }
}









再次感谢您的帮助。





Ps如果我错误地解决了这个问题,请提供示例来纠正我。





Thanks again for any help.


P.s If I am going about this wrongly, please provide examples to correct me.

推荐答案

一些事情。做一些改变。我认为不需要2个PersonLists,而且对于Persons属性,_personList应该是私有的。我也看到在for循环中也没有必要使用
A few things. Make a few changes. I don't see a need for 2 PersonLists and with the Persons Property the _personList should be private. I also saw no need to have
PersonList = obVinyl;

。还有什么是db.SaveChanges呢?在构造函数中使用它似乎很奇怪。



in the for loop either. Also what is the db.SaveChanges doing? It seems odd to have this in the constructor.

public class PersonViewModel
    {
        private IList<Person> _personList;
        ObservableCollection<Person> obVinyl = new ObservableCollection<Person>();
        public PersonViewModel()
        {
            using (var db = new PersonContext())
            {
 
                // Display all vinyl from the database

                var query = from b in db.People
 
                            orderby b.Id
 
                            select b;
 

                foreach (var item in query)
                {
                    obVinyl.Add(item);
                }
               // What is this supposed to be doing in here?
                db.SaveChanges();
            }
            _personList = obVinyl;
        }
 
        public IList<Person> Persons
        {
            get { return _personList; }
            set { _personList = value;}
        }
        private ICommand mUpdater;
        public ICommand UpdateCommand
        {
            get
            {
                if (mUpdater == null)
                    mUpdater = new Updater();
                return mUpdater;
            }
            set
            {
                mUpdater = value;
            }
        }
    }





您可以向Person对象添加另一个属性,例如hasChanged和当用户更改任何内容时,将其设置为true。如果用户添加新的Person(新列表视图项),则将Id设置为0或-1。



然后当您保存时,您将查找所有项目在您的Persons列表中有0并将它们插入到数据库中,并且hasChanged = true的那些将更新。



我没有多使用数据集但是如果有Person.Add应该有Person.Update,或者至少你可以替换数据集副本你的副本。



对不起,毕竟我认为我找不到你想要的答案......



You can add another property to the Person object say hasChanged and when the user changes anything set it to true. If the users add a new Person (new list view item) then set the Id to 0 or -1.

Then when you save, you look for all the items in your Persons list that have 0 and insert them into the database and the ones with hasChanged = true you will update.

I haven't used datasets much but if there is a Person.Add there should be a Person.Update, or at the least you could replace the dataset copy with your copy.

Sorry, After all this I don't think I quite got to an answer you were looking for...


这篇关于C#MVVM CodeFirst - Icommand - Sql DataAccess请帮助!!!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆