WPF MVVM+EF增删改查 简单示例(二) 1对1 映射
WPF MVVM+EF增删改查 简单示例(一)实现了对学生信息的管理。
现在需求发生变更,在录入学生资料的时候同时需要录入学生的图片信息,并且一名学生只能有一张图片资料。并可对学生的图片资料进行更新。
添加了那些功能,先看看效果图:


第一步:添加实体类StudentPhotoEntity.cs
public class StudentPhotoEntity
{
public int StudentId { get; set; }
public byte[] StudentPhoto { get; set; }
public virtual StudentEntity Student { get; set; }
}
第二步:修改实体类StudentEntity.cs
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; }
public virtual StudentPhotoEntity StudentPhoto { get; set; } }
第三步:添加StudentPhotoEntityMapping.cs
public class StudentPhotoEntityMapping : EntityTypeConfiguration<StudentPhotoEntity>
{
public StudentPhotoEntityMapping()
{
this.HasKey(t => t.StudentId);
this.ToTable("StudentPhoto");
this.Property(t => t.StudentPhoto).HasColumnName("StudentPhoto").HasColumnType(SqlDbType.Image.ToString()).IsRequired();
}
}
第四步:修改StudentEntityMapping.cs
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(); this.HasRequired(t => t.StudentPhoto).WithRequiredPrincipal(i => i.Student);
this.HasOptional(t => t.StudentPhoto).WithRequired(i => i.Student);
}
}
第五步:更新数据库
1,将连接字符串修改为绝对路径
2,打开“程序包管理器控制台”
3,输入Add-Migration命令 回车
4,输入Name 回车
5,输入Update-Database 回车
6,修改链接字符串
第六步:修改StudentControl.xaml在DataGrid中添加列
<DataGridTemplateColumn Header="头像" Width="100" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate >
<Grid>
<Image Source="{Binding StudentPhoto.StudentPhoto,Converter={StaticResource convertImageAndByte}}" Stretch="Fill" Width="50" Height="50" HorizontalAlignment="Center" VerticalAlignment="Center" ></Image>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
第七步:修改AddOrEditWindow.xaml添加图片输入控件
<StackPanel Grid.Row="0" Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center" Margin="20,0,0,0">
<Border BorderThickness="0.6" BorderBrush="Black">
<Image x:Name="img" Width="70" Height="70" Stretch="Fill" Source="{Binding CurrentStudentEntity.StudentPhoto.StudentPhoto,Mode=TwoWay,Converter={StaticResource convertImageAndByte}}"></Image>
</Border>
<Button Width="40" Height="20" VerticalAlignment="Bottom" Margin="10,0,0,0" Content="浏览" Click="Button_Click"> </Button>
</StackPanel>
第八步:修改AddOrEditViewModel.cs中的Save()方法
private void Save()
{
StudentEntity student = new StudentEntity()
{
StudentName = CurrentStudentEntity.StudentName,
StudentAge = CurrentStudentEntity.StudentAge,
StudentSex = IsChecked ? 0 : 1,
StudentAddress = CurrentStudentEntity.StudentAddress,
StudentPhoto = new StudentPhotoEntity()
{
StudentPhoto = CurrentStudentEntity.StudentPhoto.StudentPhoto
}
};
if (IsAdd)
{
StudentDal.Insert(student);
}
else
{
student.StudentId = CurrentStudentEntity.StudentId;
student.StudentPhoto.StudentId = CurrentStudentEntity.StudentId;
StudentDal.Update(student);
}
}
第九步:添加一个转换器类,实现图片与byte[]的相互转化
[System.Windows.Data.ValueConversion(typeof(byte[]), typeof(ImageSource))]
public class ConvertImageAndByte : System.Windows.Data.IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
byte[] binaryimagedata = value as byte[];
if (binaryimagedata == null) return "";
using (Stream imageStreamSource = new MemoryStream(binaryimagedata, false))
{ JpegBitmapDecoder jpeDecoder = new JpegBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
ImageSource imageSource = jpeDecoder.Frames[0];
return imageSource;
} } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
return "";
string path = value.ToString().Substring(8, value.ToString().Length - 8);
System.Drawing.Bitmap bitmap;
BitmapSource bmp = new BitmapImage(new Uri(path, UriKind.Absolute));
using (MemoryStream outStream = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(bmp));
enc.Save(outStream);
bitmap = new System.Drawing.Bitmap(outStream);
}
System.Drawing.Bitmap bm = new System.Drawing.Bitmap(bitmap); System.IO.MemoryStream stream = new System.IO.MemoryStream();
bm.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] imgBytes = stream.ToArray();
stream.Close(); return imgBytes;
}
}
此文仅作学习中的记录,希望对看到此文的同学有一点点的帮助。
文中如果有不正确的地方欢迎指正。
WPF MVVM+EF增删改查 简单示例(二) 1对1 映射的更多相关文章
- WPF MVVM+EF 增删改查 简单示例(一)
实现了那些功能,先看看效果图: 项目工程目录: 接下来开始具体的步骤: 第一步:在VS中新建工程 第二步:使用NuGet 安装EntityFramework 第三步:使用NuGet 安装EntityF ...
- springboot+jpa+thymeleaf增删改查的示例(转)
这篇文章介绍如何使用jpa和thymeleaf做一个增删改查的示例. 先和大家聊聊我为什么喜欢写这种脚手架的项目,在我学习一门新技术的时候,总是想快速的搭建起一个demo来试试它的效果,越简单越容易上 ...
- 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(5)-EF增删改查by糟糕的代码
原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(5)-EF增删改查by糟糕的代码 上一讲我们创建了一系列的解决方案,我们通过一个例子来看看层与层之间的关系 ...
- 分享一个自己写的MVC+EF “增删改查” 无刷新分页程序
分享一个自己写的MVC+EF “增删改查” 无刷新分页程序 一.项目之前得添加几个组件artDialog.MVCPager.kindeditor-4.0.先上几个效果图. 1.首先建立一个数 ...
- EF学习笔记-1 EF增删改查
首次接触Entity FrameWork,就感觉非常棒.它节省了我们以前写SQL语句的过程,同时也让我们更加的理解面向对象的编程思想.最近学习了EF的增删改查的过程,下面给大家分享使用EF对增删改查时 ...
- EF增删改查的优化
在EF的上一篇博客中已经对它的增删改查有了一个简单的了解.当中的改动过程是先要把要改动的内容查出来然后再进行改动.保存.它详细的过程是这种 首先当在运行查询语句的时候"EF数据上下文&quo ...
- C# EF增删改查
1.增 //1.创建一个EF数据上下文对象 MyDBEntities context=new MyDBEntities(); //2.将要添加的数据,封装成对象 Users user = new Us ...
- MVC3.0 EF增删改查的封装类
本人亲身使用EF CodeFirst,因为增删改查都是使用EF内置的一些方法,我想把它封装到一个类调用就行了.结合网上的资料和自己的整理,若有不对的地方望斧正,感激不尽.直接上代码吧.我就用新闻的增删 ...
- iOS sqlite 增删改查 简单封装(基于 FMDB)
/** * 对 sqlite 的使用进行简单封装,仅涉及简单的单表 增删改查 * * 基于 FMDB * * 操作基于 model ,数据库表字段与 model 属性一一对应,对 model 整 ...
随机推荐
- 【C#】万事开头难(二)<机房重构>
前言 机房将要进行完了,之所以仍然使用这个题目,是由于我想告诉自己.无论面对多么未知的事物.不要害怕,去做就好.在这么多天的机房重构中,发现了好多问题,也攻克了好多问题,今天,就把我解决的问题分享给大 ...
- [Compose] 8. A curated collection of Monoids and their uses
const { List } = require('immutable-ext'); const Right = x => ({ chain : f => f(x), ap : other ...
- 逐步把Nginx及Redis引入项目组之负载均衡技术调研初版总结
本篇以一个Nginx服务.两个Tomcat服务.一个Redis搭建一个负载均衡环境,由于就一台电脑暂以随机分配client请求策略开展,详细工作中推荐以IP地址来实现client请求的动态负载策略.省 ...
- Go 快速入门
入门 Go 语言需要多久?答案是 -- 读完这篇文章的时间!不妨找一个周末的下午,踏上 Go 之旅吧! 更新记录: 2016.12.12: 完成重制 2016.11.02: 增加重点理解和参考链接 2 ...
- web.xml 中的listener、 filter、servlet 加载顺序及其详解(转)
在项目中总会遇到一些关于加载的优先级问题,近期也同样遇到过类似的,所以自己查找资料总结了下,下面有些是转载其他人的,毕竟人家写的不错,自己也就不重复造轮子了,只是略加点了自己的修饰. 首先可以肯定的是 ...
- Unity UGUI——Rect Transform包(Anchors)
Anchors(锚)操作演示 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvTXJfQUhhbw==/font/5a6L5L2T/fontsize/400/ ...
- C#7模范和实践
C# 7 中的模范和实践 原文地址:https://www.infoq.com/articles/Patterns-Practices-CSharp-7 关键点 遵循 .NET Framework ...
- Android Studio运行main方法
这样想做一些测试就很简单了 实现步骤如下: 1.当前项目右键->new->Module->Java Library 2.修改你创建javaLib的build.gradle文件 改为( ...
- struts2和velocity整合问题
以下是我第一次使用velocity的时候写的 2012-03-12 话说struts真够懒的,都把velocity-1.6.4.jar放到他自己的lib里边了,就不给放全了,搞得新手太郁闷了.stru ...
- Java获取URL对应的资源
Java获取URL对应的资源 认识IP.认识URL是进行网络编程的第一步.java.net.URL提供了丰富的URL构建方式,并可以通过java.net.URL来获取资源. 一.认识URL ...