WPF mvvm+ef Additions and Deletions Simple example (ii) 1-to-1 mapping

Source: Internet
Author: User

WPF mvvm+ef Additions and deletions simple example (a) the management of student information is realized.

Now the need to change, in the entry of student data at the same time need to enter the student's picture information, and a student can only have a picture information. And the student's picture information can be updated.

Add those features, first look at:

First step: Add entity class StudentPhotoEntity.cs

  public class studentphotoentity    {public        int StudentID {get; set;}        Public byte[] Studentphoto {get; set;}        Public virtual studententity Student {get; set;}    }

Step Two: Modify the entity class 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;}    }

Step Three: Add 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 ();        }    }

Fourth Step: Modify 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); }    }

Fifth step: Update the database

1. Modify the connection string to an absolute path
2. Open the Package Manager console
3, Input add-migration command enter
4, enter name return
5, enter Update-database return
6, modify the link string


Sixth step: Modify Studentcontrol.xaml to add columns to the DataGrid

   <datagridtemplatecolumn header= "Avatar" width= ">                    <DataGridTemplateColumn.CellTemplate>                        < DataTemplate  >                            <Grid>                                <image source= "{Binding studentphoto.studentphoto,converter={ StaticResource Convertimageandbyte}} "Stretch=" Fill "width=" "height=" horizontalalignment= "Center" Verticalalignment= "Center" ></Image>                            </Grid>                        </DataTemplate>                    </ Datagridtemplatecolumn.celltemplate>                </DataGridTemplateColumn>

Seventh Step: Modify Addoreditwindow.xaml Add picture input control

  <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= " Stretch= "Fill" source= "{Binding currentstudententity.studentphoto.studentphoto,mode=twoway,converter={ StaticResource Convertimageandbyte}} "></Image>            </Border>            <button  width=" Max "Height = "Verticalalignment=" "Bottom" margin= "10,0,0,0" content= "Browse" click= "Button_Click" > </Button>        </ Stackpanel>

Eighth step: Modify the Save () method in AddOrEditViewModel.cs

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); } }

Nineth Step: Add a translator class to transform the picture and byte[]

[System.Windows.Data.ValueConversion (typeof (Byte[]), typeof(ImageSource))] public classConvertImageAndByte:System.Windows.Data.IValueConverter {public Object Convert (object value, Type TargetType, Objectparameter, System.Globalization.CultureInfo culture) {byte[] Binaryimagedata = value as Byte[]; if (Binaryimagedata = = null) return ""; using (Stream Imagestreamsource = new MemoryStream (Binaryimagedata, False) {Jpegbitmapdecoder Jpedecoder = newJpegbitmapdecoder (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  Memor Ystream ()) {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;}              

This article is only for the study of records, I hope to see this article of the students have a little help.

If there is an incorrect place in the text, please correct me.

WPF mvvm+ef Additions and Deletions Simple example (ii) 1-to-1 mapping

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.