WPF MVVM+EF 增删该查 简单示例(一)

实现了那些功能,先看看效果图:

项目工程目录:

接下来开始具体的步骤:

第一步:在VS中新建工程

第二步:使用NuGet 安装EntityFramework

第三步:使用NuGet 安装EntityFramework.SqlSreverCompact

第四步:在Entities文件夹下添加StudentEntity类

1  public class StudentEntity
2     {
3         public int StudentId { get; set; }
4         public string StudentName { get; set; }
5         public int StudentAge { get; set; }
6         public int StudentSex { get; set; }
7         public string StudentAddress { get; set; }
8
9     }

第五步:在Mappings文件夹下添加实体映射StudentEntityMapping类

 public class StudentEntityMapping : EntityTypeConfiguration<StudentEntity>
    {
        public StudentEntityMapping()
        {
            this.HasKey(t => t.StudentId);

            this.ToTable("Student");

            this.Property(t => t.StudentId).HasColumnName("StudentId").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).IsRequired();
            this.Property(t => t.StudentName).HasColumnName("StudentName").HasColumnType(SqlDbType.NVarChar.ToString()).HasMaxLength(50).IsRequired();
            this.Property(t => t.StudentAge).HasColumnName("StudentAge").HasColumnType(SqlDbType.Int.ToString()).IsRequired();
            this.Property(t => t.StudentSex).HasColumnName("StudentSex").HasColumnType(SqlDbType.Int.ToString()).IsRequired();
            this.Property(t => t.StudentAddress).HasColumnName("StudentAddress").HasColumnType(SqlDbType.NVarChar.ToString()).HasMaxLength(200).IsRequired();
        }
    }

第六步:在Dal文件夹下添加StudentDataContext类

  public class StudentDataContext : DbContext
    {

        public StudentDataContext()
            : base("StudentDataContext")
        {

        }
        public DbSet<StudentEntity> Students { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.AddFromAssembly(typeof(StudentDataContext).Assembly);
        }
    }

第七步:在AppConfig添加数据库的连接字符串

注意此处的路径必须为绝对路径

<connectionStrings>
<add name="StudentDataContext" providerName="System.Data.SqlServerCe.4.0" connectionString="Data Source=E:\Sample\DataBase\StudentDataContext.sdf" />
</connectionStrings>

第八步:在NuGet包管理器中打开“程序包管理器控制台”

第九步:生成Migrations文件并创建数据库

A,在打开的程序包管理器控制台中输入  enable-migrations 命令此时会自动在工程目录下创建一个Migrations文件夹和Configuration.cs

B,打开Configuration.cs 修改 AutomaticMigrationsEnabled = true;

C,在打开的程序包管理器控制台中输入update-database

D,执行完成后就会在E:\Sample\DataBase\StudentDataContext.sdf下创建好数据库,将此数据库包含在项目中并将其包含在项目中,并将其设置为始终复制,编译项目,

并再次修改App.Config中的连接字符串。connectionString="Data Source=DataBase\StudentDataContext.sdf"

第十步:在Dal下添加一个用于操作数据的类StudentDal

  public  class StudentDal
    {
        StudentDataContext studentDataContext = new StudentDataContext();

        public List<StudentEntity> GetAllStudent()
        {
            return studentDataContext.Students.ToList();
        }

        public void Insert(StudentEntity studentEntity)
        {
            studentDataContext.Students.Add(studentEntity);
            studentDataContext.SaveChanges();
        }
        public void Delete(StudentEntity studentEntity)
        {
            studentDataContext.Students.Remove(studentEntity);
            studentDataContext.SaveChanges();
        }
        public void Update(StudentEntity studentEntity)
        {
            var id = studentDataContext.Students.Find(studentEntity.StudentId);
            var entry = studentDataContext.Entry(id);
            entry.CurrentValues.SetValues(studentEntity);
            entry.Property(p => p.StudentId).IsModified = false;
            studentDataContext.SaveChanges();
        }
    }

第十一步:在Views文件加下添加AddOrEditWindow.xaml和StudentControl.xaml

StudentControl.xaml

<UserControl x:Class="Sample.Views.StudentControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:viewModel="clr-namespace:Sample.ViewModels"
             xmlns:convert="clr-namespace:Sample.Convert"
             mc:Ignorable="d" >
    <UserControl.Resources>
        <Style  TargetType="{x:Type DataGridColumnHeader}">
            <Setter Property="HorizontalContentAlignment" Value="Center" />
            <Setter Property="VerticalContentAlignment" Value="Center" />
        </Style>
        <convert:ConvertIntToString x:Key="convertIntToString" ></convert:ConvertIntToString>
    </UserControl.Resources>
    <UserControl.DataContext>
        <viewModel:StudentViewModel></viewModel:StudentViewModel>
    </UserControl.DataContext>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="40"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>
        <Button Width="80" Height="30" Content="添加" HorizontalAlignment="Right" Margin="0,0,20,0" Grid.Row="0" Command="{Binding AddCommand}"></Button>
        <Button Width="80" Height="30" Content="刷新" HorizontalAlignment="Right" Margin="0,0,120,0" Grid.Row="0" Command="{Binding RefreshCommand}"/>
        <Rectangle Fill="Black" Height="1" Grid.Row="0" VerticalAlignment="Bottom"></Rectangle>
        <DataGrid Grid.Row="1" ItemsSource="{Binding Students}"  SelectedItem="{Binding SelectStudentEntity, Mode=TwoWay}"  CanUserSortColumns="False"  CanUserResizeColumns="False" CanUserResizeRows="False" SelectionMode="Extended"
                            CanUserReorderColumns="False"  RowHeaderWidth="0" CanUserAddRows="False"  AutoGenerateColumns="False"  EnableRowVirtualization="False" GridLinesVisibility="None"  Margin="5" >
            <DataGrid.Columns>
                <DataGridTemplateColumn Header="编号" Width="80" >
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Grid>
                                <TextBlock Text="{Binding StudentId}" HorizontalAlignment="Center" VerticalAlignment="Center" ></TextBlock>
                            </Grid>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTemplateColumn Header="姓名" Width="120" >
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Grid>
                                <TextBlock Text="{Binding StudentName}" HorizontalAlignment="Center" VerticalAlignment="Center" ></TextBlock>
                            </Grid>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTemplateColumn Header="性别" Width="80" >
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Grid>
                                <TextBlock Text="{Binding StudentSex,Converter={StaticResource convertIntToString}}" HorizontalAlignment="Center" VerticalAlignment="Center" ></TextBlock>
                            </Grid>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTemplateColumn Header="年龄" Width="80" >
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Grid>
                                <TextBlock Text="{Binding StudentAge}" HorizontalAlignment="Center" VerticalAlignment="Center" ></TextBlock>
                            </Grid>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTemplateColumn Header="家庭住址" Width="180" >
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Grid>
                                <TextBlock Text="{Binding StudentAddress}" HorizontalAlignment="Center" VerticalAlignment="Center" ></TextBlock>
                            </Grid>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTemplateColumn  Width="150" Header="操作">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Grid>
                                <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">

                                    <Button    Width="40" Height="20" Content="编辑"   FontSize="10"   Command="{Binding DataContext.EditCommand, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=UserControl}}"  ></Button>
                                    <Button    Width="40" Height="20"  Margin="10,0,0,0" Content="删除" FontSize="10" Command="{Binding DataContext.DeleteCommand, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=UserControl}}" ></Button>
                                </StackPanel>
                            </Grid>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>

    </Grid>
</UserControl>

AddOrEditWindow.xaml

 1 <Window x:Class="Sample.Views.AddOrEditWindow"
 2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 4         xmlns:viewModel="clr-namespace:Sample.ViewModels"
 5         Title="AddOrEditWindow" Height="280" Width="300" WindowStartupLocation="CenterScreen" Topmost="True" ResizeMode="NoResize">
 6     <Window.DataContext>
 7         <viewModel:AddOrEditViewModel></viewModel:AddOrEditViewModel>
 8     </Window.DataContext>
 9     <Grid>
10         <Grid.RowDefinitions>
11             <RowDefinition Height="50"></RowDefinition>
12             <RowDefinition Height="50"></RowDefinition>
13             <RowDefinition Height="50"></RowDefinition>
14             <RowDefinition Height="50"></RowDefinition>
15             <RowDefinition Height="*"></RowDefinition>
16         </Grid.RowDefinitions>
17         <Grid.ColumnDefinitions>
18             <ColumnDefinition Width="100"></ColumnDefinition>
19             <ColumnDefinition Width="*"></ColumnDefinition>
20         </Grid.ColumnDefinitions>
21         <Label Grid.Row="0" Grid.Column="0" Content="学生姓名:" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,10,0"></Label>
22         <Label Grid.Row="1" Grid.Column="0" Content="学生年龄:" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,10,0"></Label>
23         <Label Grid.Row="2" Grid.Column="0" Content="学生性别:" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,10,0"></Label>
24         <Label Grid.Row="3" Grid.Column="0" Content="家庭住址:" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,10,0"></Label>
25         <TextBox Grid.Row="0" Grid.Column="1" Width="160" Height="25" Text="{Binding CurrentStudentEntity.StudentName,Mode=TwoWay}"></TextBox>
26         <TextBox Grid.Row="1" Grid.Column="1" Width="160" Height="25" Text="{Binding CurrentStudentEntity.StudentAge,Mode=TwoWay}"></TextBox>
27         <StackPanel Orientation="Horizontal" Grid.Row="2" Grid.Column="1" Margin="20,0,0,0">
28             <RadioButton  GroupName="sex"  Content="男" VerticalAlignment="Center" IsChecked="{Binding IsChecked,Mode=TwoWay}"></RadioButton>
29             <RadioButton  GroupName="sex"   Content="女" VerticalAlignment="Center"  Margin="20,0,0,0"></RadioButton>
30         </StackPanel>
31         <TextBox Grid.Row="3" Grid.Column="1" Width="160" Height="25" Text="{Binding CurrentStudentEntity.StudentAddress,Mode=TwoWay}"></TextBox>
32         <Rectangle Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2" Fill="Black" Height="1" VerticalAlignment="Bottom"></Rectangle>
33         <Button Content="保存" Width="80" Height="30" Grid.Row="4" Grid.Column="1" Command="{Binding SaveCommand}"></Button>
34     </Grid>
35 </Window>

第十二步:在ViewModels中添加AddOrEditViewModel.cs和StudentViewModel.cs

StudentViewModel.cs代码:

 public class StudentViewModel : ViewModelBase
    {
        private List<StudentEntity> _students;
        public List<StudentEntity> Students
        {
            get { return _students; }
            set
            {
                if (_students != value)
                {
                    _students = value;
                    this.OnPropertyChanged(r => r.Students);
                }
            }
        }

        private StudentEntity _studentEntity;
        public StudentEntity SelectStudentEntity
        {
            get { return _studentEntity; }
            set
            {
                if (_studentEntity != value)
                {
                    _studentEntity = value;
                    this.OnPropertyChanged(r => r.SelectStudentEntity);
                }
            }
        }

        public ICommand AddCommand { get; set; }
        public ICommand RefreshCommand { get; set; }
        public ICommand EditCommand { get; set; }
        public ICommand DeleteCommand { get; set; }

        private StudentDal studentDal = null;
        public StudentViewModel()
        {
            studentDal = new StudentDal();
            AddCommand = new DelegateCommand(AddStuddent);
            RefreshCommand = new DelegateCommand(Refresh);
            EditCommand = new DelegateCommand(EditStudent);
            DeleteCommand = new DelegateCommand(DeleteStudent);
            Students = new  List<StudentEntity>();
            Students = studentDal.GetAllStudent();
        }

        private void AddStuddent()
        {
            AddOrEditWindow addOrEditWindow = new AddOrEditWindow();
            addOrEditWindow.Show();
            var addOrEditViewModel = (addOrEditWindow.DataContext as AddOrEditViewModel);
            addOrEditViewModel.CurrentStudentEntity = new StudentEntity();
            addOrEditViewModel.IsAdd = true;
            addOrEditViewModel.StudentDal = studentDal;
        }

        private void Refresh()
        {
            Students = studentDal.GetAllStudent();
        }
        private void EditStudent()
        {
           AddOrEditWindow  addOrEditWindow = new AddOrEditWindow();
           addOrEditWindow.Show();
           var addOrEditViewModel = (addOrEditWindow.DataContext as AddOrEditViewModel);
           addOrEditViewModel.CurrentStudentEntity = SelectStudentEntity;
           addOrEditViewModel.IsAdd = false;
           addOrEditViewModel.StudentDal = studentDal;
        }

        private void DeleteStudent()
        {
            studentDal.Delete(SelectStudentEntity);
        }

    }

AddOrEditViewModel.cs代码:

 public class AddOrEditViewModel :ViewModelBase

        private StudentEntity _currentStudentEntity;
        public StudentEntity CurrentStudentEntity
        {
            get { return _currentStudentEntity; }
            set
            {
                if (_currentStudentEntity != value)
                {
                    _currentStudentEntity = value;
                    if (_currentStudentEntity.StudentSex == 0)
                    {
                        IsChecked = true;
                    }
                    else
                    {
                        IsChecked = false ;
                    }

                    this.OnPropertyChanged(r => r.CurrentStudentEntity);
                }
            }
        }

        private bool _isChecked;
        public bool IsChecked
        {
            get { return _isChecked; }
            set
            {
                if (_isChecked != value)
                {
                    _isChecked = value;
                    this.OnPropertyChanged(r => r.IsChecked);
                }
            }
        }

        public StudentDal StudentDal { get; set; }

        private bool _isAdd = false;

        public bool IsAdd
        {
            get { return _isAdd; }
            set
            {
                if (_isAdd != value)
                {
                    _isAdd = value;
                    this.OnPropertyChanged(r => r.IsAdd);
                }
            }
        }
        public ICommand SaveCommand { get; set; }

        public AddOrEditViewModel()
        {
            SaveCommand = new DelegateCommand(Save);
        }

        private void Save()
        {
            StudentEntity student = new StudentEntity();
            student.StudentName = CurrentStudentEntity.StudentName;
            student.StudentAge = CurrentStudentEntity.StudentAge;
            student.StudentSex = IsChecked ?0:1;
            student.StudentAddress = CurrentStudentEntity.StudentAddress;
            if (IsAdd)
            {
                StudentDal.Insert(student);
            }
            else
            {
                student.StudentId = CurrentStudentEntity.StudentId;
                StudentDal.Update(student);
            }
        }
    }

至于ViewModelBase.cs和DelegateCommand.cs这两个类可以在网上查查,这里就不贴了。

第十三步:对于性别的转换单独写了一个转化器ConvertIntToString.cs其主要功能是将数据库中的0和1转换为 “男”和“女”显示

[System.Windows.Data.ValueConversion(typeof(int), typeof(string))]
    public class ConvertIntToString : System.Windows.Data.IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string sex="";
            if (int.Parse(value.ToString()) == 0)
            {
                sex = "男";
            }
            else
            {
                sex = "女";
            }
            return sex;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

第十四步:在MainWindow.xaml中添加StudentControl控件

此文仅作学习中的记录,希望对看到此文的同学有一点点的帮助。

文中如果有不正确的地方欢迎指正。

时间: 2024-10-04 23:03:30

WPF MVVM+EF 增删该查 简单示例(一)的相关文章

WPF MVVM+EF增删改查 简单示例(二) 1对1 映射

WPF MVVM+EF增删改查 简单示例(一)实现了对学生信息的管理. 现在需求发生变更,在录入学生资料的时候同时需要录入学生的图片信息,并且一名学生只能有一张图片资料.并可对学生的图片资料进行更新. 添加了那些功能,先看看效果图: 第一步:添加实体类StudentPhotoEntity.cs public class StudentPhotoEntity { public int StudentId { get; set; } public byte[] StudentPhoto { get;

EF增删库查

public async Task<bool> Add(fu_ocrresult model) { using (var db = new GENEModel()) { //1.将实体对象 a.加入 EF 对象容器中,并 b.获取 伪包装类对象 DbEntityEntry<fu_ocrresult> entry = db.Entry<fu_ocrresult>(model); //2.包装类对象的状态设置 entry.State = EntityState.Added;

EF-增删改查简单示例

前言: 数据上下文: NorthwindContext, 数据成员对象: public class Province(){...} 1,新增 Province province = new Province { ProvinceID = Guid.NewGuid(), ProvinceNo = "100000", ProvinceName = "北京" }; using (NorthwindContext db = new NorthwindContext()) {

最简单的通讯录,实现了联系人的 增删该查

原文:最简单的通讯录,实现了联系人的 增删该查 源代码下载地址:http://www.zuidaima.com/share/1550463724014592.htm omcat servlet jsp db 最简单的通讯录 实现了联系人的 增删该查 数据库在压缩包内 经验证该分享代码有乱码的问题,界面也很粗糙,导入db也会有乱码问题.大家可以酌情下载,不过对初级工程师有借鉴意义. 登陆页面 http://localhost:端口/项目名称/login.html 管理页面 jdbc的连接配置需要手

WPF MVVM初体验

首先MVVM设计模式的结构, Views: 由Window/Page/UserControl等构成,通过DataBinding与ViewModels建立关联: ViewModels:由一组命令,可以绑定的属性,操作逻辑构成:因为View与ViewModel进行了解耦,我们可以对ViewModel进行Unit Test: Models:可以是实体对象或者Web服务: 下面通过一个简单的例子,来介绍一些WPF MVVM模式.示例将展示一个图片浏览器,打开图片,放大/缩小图片大小.首先项目结构: UI

WPF MVVM模式的一些理解

/*本文转自 http://www.cnblogs.com/sirkevin/archive/2012/11/28/2793471.html */ 使用WPF+Mvvm开发一年多,期间由于对Mvvm模式的理解不足,遇到了很多问题,也绕了很多弯子:网上提供的Mvvm的示例比较简单,实际项目中的需求也各种各样.不过经过几个项目,也有了一些对Mvvm模式的理解: 1. Mvvm是什么,Mvvm是怎么来的?Mvvm模式广泛应用在WPF项目开发中,使用此模式可以把UI和业务逻辑分离开,使UI设计人员和业务

WPF MVVM学习

转自https://my.oschina.net/unpluggedcoder/blog/536301 简介 简单的三层架构示例和 GLUE(胶水)代码问题 第一步:最简单的 MVVM 示例 - 把后台代码移到类中 第二步:添加绑定 - 消灭后台代码 第三步:添加执行动作和"INotifyPropertyChanged"接口 第四步:在 ViewModel 中解耦执行动作 第五步:利用 PRISM WPF MVVM 的视频演示 简介 从我们还是儿童到学习成长为成年人,生命一直都在演变.

WPF MVVM从入门到精通7:关闭窗口和打开新窗口

原文:WPF MVVM从入门到精通7:关闭窗口和打开新窗口 WPF MVVM从入门到精通1:MVVM模式简介 WPF MVVM从入门到精通2:实现一个登录窗口 WPF MVVM从入门到精通3:数据绑定 WPF MVVM从入门到精通4:命令和事件 WPF MVVM从入门到精通5:PasswordBox的绑定 WPF MVVM从入门到精通6:RadioButton等一对多控件的绑定 WPF MVVM从入门到精通7:关闭窗口和打开新窗口 WPF MVVM从入门到精通8:数据验证 完整示例代码下载Log

WPF MVVM从入门到精通5:PasswordBox的绑定

原文:WPF MVVM从入门到精通5:PasswordBox的绑定 ? WPF MVVM从入门到精通1:MVVM模式简介 WPF MVVM从入门到精通2:实现一个登录窗口 WPF MVVM从入门到精通3:数据绑定 WPF MVVM从入门到精通4:命令和事件 WPF MVVM从入门到精通5:PasswordBox的绑定 WPF MVVM从入门到精通6:RadioButton等一对多控件的绑定 WPF MVVM从入门到精通7:关闭窗口和打开新窗口 WPF MVVM从入门到精通8:数据验证 完整示例代