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

项目工程目录:

接下来开始具体的步骤:

第一步:在VS中新建工程

第二步:使用NuGet 安装EntityFramework

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

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

  public class StudentEntity
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public int StudentAge { get; set; }
public int StudentSex { get; set; }
public string StudentAddress { get; set; } }

第五步:在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().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().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=""></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Button Width="" Height="" Content="添加" HorizontalAlignment="Right" Margin="0,0,20,0" Grid.Row="" Command="{Binding AddCommand}"></Button>
<Button Width="" Height="" Content="刷新" HorizontalAlignment="Right" Margin="0,0,120,0" Grid.Row="" Command="{Binding RefreshCommand}"/>
<Rectangle Fill="Black" Height="" Grid.Row="" VerticalAlignment="Bottom"></Rectangle>
<DataGrid Grid.Row="" ItemsSource="{Binding Students}" SelectedItem="{Binding SelectStudentEntity, Mode=TwoWay}" CanUserSortColumns="False" CanUserResizeColumns="False" CanUserResizeRows="False" SelectionMode="Extended"
CanUserReorderColumns="False" RowHeaderWidth="" CanUserAddRows="False" AutoGenerateColumns="False" EnableRowVirtualization="False" GridLinesVisibility="None" Margin="" >
<DataGrid.Columns>
<DataGridTemplateColumn Header="编号" Width="" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding StudentId}" HorizontalAlignment="Center" VerticalAlignment="Center" ></TextBlock>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="姓名" Width="" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding StudentName}" HorizontalAlignment="Center" VerticalAlignment="Center" ></TextBlock>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="性别" Width="" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding StudentSex,Converter={StaticResource convertIntToString}}" HorizontalAlignment="Center" VerticalAlignment="Center" ></TextBlock>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="年龄" Width="" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding StudentAge}" HorizontalAlignment="Center" VerticalAlignment="Center" ></TextBlock>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="家庭住址" Width="" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding StudentAddress}" HorizontalAlignment="Center" VerticalAlignment="Center" ></TextBlock>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Width="" Header="操作">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center"> <Button Width="" Height="" Content="编辑" FontSize="" Command="{Binding DataContext.EditCommand, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=UserControl}}" ></Button>
<Button Width="" Height="" Margin="10,0,0,0" Content="删除" FontSize="" Command="{Binding DataContext.DeleteCommand, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=UserControl}}" ></Button>
</StackPanel>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid> </Grid>
</UserControl>

AddOrEditWindow.xaml

 <Window x:Class="Sample.Views.AddOrEditWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:viewModel="clr-namespace:Sample.ViewModels"
Title="AddOrEditWindow" Height="" Width="" WindowStartupLocation="CenterScreen" Topmost="True" ResizeMode="NoResize">
<Window.DataContext>
<viewModel:AddOrEditViewModel></viewModel:AddOrEditViewModel>
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height=""></RowDefinition>
<RowDefinition Height=""></RowDefinition>
<RowDefinition Height=""></RowDefinition>
<RowDefinition Height=""></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width=""></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Label Grid.Row="" Grid.Column="" Content="学生姓名:" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,10,0"></Label>
<Label Grid.Row="" Grid.Column="" Content="学生年龄:" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,10,0"></Label>
<Label Grid.Row="" Grid.Column="" Content="学生性别:" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,10,0"></Label>
<Label Grid.Row="" Grid.Column="" Content="家庭住址:" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,10,0"></Label>
<TextBox Grid.Row="" Grid.Column="" Width="" Height="" Text="{Binding CurrentStudentEntity.StudentName,Mode=TwoWay}"></TextBox>
<TextBox Grid.Row="" Grid.Column="" Width="" Height="" Text="{Binding CurrentStudentEntity.StudentAge,Mode=TwoWay}"></TextBox>
<StackPanel Orientation="Horizontal" Grid.Row="" Grid.Column="" Margin="20,0,0,0">
<RadioButton GroupName="sex" Content="男" VerticalAlignment="Center" IsChecked="{Binding IsChecked,Mode=TwoWay}"></RadioButton>
<RadioButton GroupName="sex" Content="女" VerticalAlignment="Center" Margin="20,0,0,0"></RadioButton>
</StackPanel>
<TextBox Grid.Row="" Grid.Column="" Width="" Height="" Text="{Binding CurrentStudentEntity.StudentAddress,Mode=TwoWay}"></TextBox>
<Rectangle Grid.Row="" Grid.Column="" Grid.ColumnSpan="" Fill="Black" Height="" VerticalAlignment="Bottom"></Rectangle>
<Button Content="保存" Width="" Height="" Grid.Row="" Grid.Column="" Command="{Binding SaveCommand}"></Button>
</Grid>
</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 == )
{
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 ?:;
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()) == )
{
sex = "男";
}
else
{
sex = "女";
}
return sex;
} public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}

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

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

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

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

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

    WPF MVVM+EF增删改查 简单示例(一)实现了对学生信息的管理. 现在需求发生变更,在录入学生资料的时候同时需要录入学生的图片信息,并且一名学生只能有一张图片资料.并可对学生的图片资料进行更新. ...

  2. springboot+jpa+thymeleaf增删改查的示例(转)

    这篇文章介绍如何使用jpa和thymeleaf做一个增删改查的示例. 先和大家聊聊我为什么喜欢写这种脚手架的项目,在我学习一门新技术的时候,总是想快速的搭建起一个demo来试试它的效果,越简单越容易上 ...

  3. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(5)-EF增删改查by糟糕的代码

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(5)-EF增删改查by糟糕的代码 上一讲我们创建了一系列的解决方案,我们通过一个例子来看看层与层之间的关系 ...

  4. 分享一个自己写的MVC+EF “增删改查” 无刷新分页程序

    分享一个自己写的MVC+EF “增删改查” 无刷新分页程序 一.项目之前得添加几个组件artDialog.MVCPager.kindeditor-4.0.先上几个效果图.      1.首先建立一个数 ...

  5. EF学习笔记-1 EF增删改查

    首次接触Entity FrameWork,就感觉非常棒.它节省了我们以前写SQL语句的过程,同时也让我们更加的理解面向对象的编程思想.最近学习了EF的增删改查的过程,下面给大家分享使用EF对增删改查时 ...

  6. EF增删改查的优化

    在EF的上一篇博客中已经对它的增删改查有了一个简单的了解.当中的改动过程是先要把要改动的内容查出来然后再进行改动.保存.它详细的过程是这种 首先当在运行查询语句的时候"EF数据上下文&quo ...

  7. C# EF增删改查

    1.增 //1.创建一个EF数据上下文对象 MyDBEntities context=new MyDBEntities(); //2.将要添加的数据,封装成对象 Users user = new Us ...

  8. MVC3.0 EF增删改查的封装类

    本人亲身使用EF CodeFirst,因为增删改查都是使用EF内置的一些方法,我想把它封装到一个类调用就行了.结合网上的资料和自己的整理,若有不对的地方望斧正,感激不尽.直接上代码吧.我就用新闻的增删 ...

  9. iOS sqlite 增删改查 简单封装(基于 FMDB)

    /** *  对 sqlite 的使用进行简单封装,仅涉及简单的单表 增删改查 * *  基于 FMDB * *  操作基于 model ,数据库表字段与 model 属性一一对应,对 model 整 ...

随机推荐

  1. 常用JS验证函数总结

    JS验证Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/- ...

  2. 基于 Android NDK 的学习之旅-----JNI LOG 打印

    程序都是调出来的. 下面我介绍下JNI层的log打印方法的使用,类似与Android sdk提供的log 1.Android 应用层 MainActivity.java 主要功能代码 a)       ...

  3. [React Router v4] Render Catch-All Routes with the Switch Component

    There are many cases where we will need a catch-all route in our web applications. This can include ...

  4. ssh连接上腾讯云、华为云Linux服务器,一会就自动断开

    客户端向服务端发送心跳 依赖 ssh 客户端定时发送心跳,putty.SecureCRT.XShell 都有这个功能. Linux / Unix 下,编辑 ssh 配置文件: # vim /etc/s ...

  5. js进阶 9-6 js如何通过name访问指定指定表单控件

    js进阶 9-6 js如何通过name访问指定指定表单控件 一.总结 一句话总结:form中控件的三种访问方式:2formElement 1document 1.form中控件的三种访问方式? 1.f ...

  6. C#基础readonly 与const

    readonly 与 const readonly是运行时常量,const是编译期常量(在编译过程中已经把使用该值的都用值替代,不分配内存)readonly灵活性高,const效率高 readonly ...

  7. 【u220】生日礼物

    Time Limit: 1 second Memory Limit: 128 MB [问题描述] 一对双胞胎兄妹同一天过生日,这一天,他们的朋友给他俩送来了礼物,每个人送的礼物都是2本书,一本给哥哥, ...

  8. 【u240】棋子放置

    Time Limit: 1 second Memory Limit: 128 MB 小虎刚刚上了幼儿园,老师让他做一个家庭作业:首先画3行格子,第一行有三个格子,第二行有2个格子,第三行有1个格子. ...

  9. 并发新特性—Executor 框架与线程池

    兰亭风雨 · 更新于 2018-11-14 09:00:31 并发新特性-Executor 框架与线程池 Executor 框架简介 在 Java 5 之后,并发编程引入了一堆新的启动.调度和管理线程 ...

  10. 【BZOJ 1016】 [JSOI2008]最小生成树计数(matrix-tree定理做法)

    [题目链接]:http://www.lydsy.com/JudgeOnline/problem.php?id=1016 [题意] [题解] /* 接上一篇文章; 这里用matrix-tree定理搞最小 ...