C#WPF实体框架代码需要第一个帮助!请! [英] C# WPF Entity Framework Code First Help Needed! Please!

查看:109
本文介绍了C#WPF实体框架代码需要第一个帮助!请!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家早上好,我真的需要一些帮助。



我开始这个小项目来帮助我学习,而我正在阅读O'Reilly的Code First书。我理解如何创建数据库,我也可以使用我从WPF应用程序提供的数据填充表格,即一些文本框,打开对话框/图像控件。



我的问题是我不明白如何使用codefirst从我的表中检索我的数据。

我尝试使用context.sqlquery并且它只会引发我的错误。



这是我的型号:

Good morning everyone, I really need some help.

I started this little project to help me study, while I am reading through O'Reilly's Code First book. I understand how to create a database and I can also populate my table with data that I provide from a WPF application, namely a few textboxes, open dialog/ image control.

My problem is that I don't understand how to retrieve my data from my table, using codefirst.
I have tried using the context.sqlquery and it just throws me errors.

Here is my Model:

namespace BusinessModel
{
    public class Vinyl
    {
        public int VinylId { get; set; }

        public string Name { get; set; }
        public string VinylLabel { get; set; }
        public string Genre { get; set; }
        public string SubGenre { get; set; }
        public byte[] Photo { get; set; }
        public string Url { get; set; }
    }

}





这是我的DataAccess:



Here is my DataAccess:

public class VinylContext : DbContext
    {
        public DbSet<Vinyl> VinylSet { get; set; }
    }





这是我添加条目的Xaml:



Here is my Xaml for adding an entry:

<Grid Margin="0,0,-226,-26">
        <Button x:Name="btnSave" Content="Save" HorizontalAlignment="Left" Margin="432,288,0,0" VerticalAlignment="Top" Width="75" Click="btnSave_Click"/>
        <TextBox x:Name="tbName" HorizontalAlignment="Left" Height="23" Margin="10,74,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <TextBox x:Name="tbVinylLabel" HorizontalAlignment="Left" Height="23" Margin="10,133,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <TextBox x:Name="tbGenre" HorizontalAlignment="Left" Height="23" Margin="10,192,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <TextBox x:Name="tbSubGenre" HorizontalAlignment="Left" Height="23" Margin="10,251,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <Label x:Name="lblName" Content="Name" HorizontalAlignment="Left" Margin="10,43,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.245,0.51"/>
        <Label Content="Add New Vinyl" Margin="10,10,10,0" VerticalAlignment="Top" FontSize="16" FontWeight="Bold"/>
        <Label x:Name="lblVinylLabel" Content="Vinyl Label" HorizontalAlignment="Left" Margin="10,102,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.245,0.51"/>
        <Label x:Name="lblGenre" Content="Genre" HorizontalAlignment="Left" Margin="10,161,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.245,0.51"/>
        <Label x:Name="lblSubGenre" Content="Sub Genre" HorizontalAlignment="Left" Margin="10,220,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.245,0.51"/>
        <Button x:Name="btnUpload" Content="Upload" HorizontalAlignment="Left" Margin="10,288,0,0" VerticalAlignment="Top" Width="75" Click="btnUpload_Click"/>
        <Label x:Name="lblImageUpload" Visibility="Hidden" Content="Upload Image" HorizontalAlignment="Right" Margin="0,284,90,0" VerticalAlignment="Top" RenderTransformOrigin="0.245,0.51" Width="337"/>
        <Label x:Name="lblUrl" Content="Website" HorizontalAlignment="Left" Margin="135,46,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.245,0.51"/>
        <TextBox x:Name="tbUrl" HorizontalAlignment="Left" Height="23" Margin="135,74,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="292" Text="http://"/>
        <Image x:Name="imgPreview" HorizontalAlignment="Left" Height="141" Margin="135,133,0,0" VerticalAlignment="Top" Width="292"/>
        <Label x:Name="lblImage" Content="Image Preview" HorizontalAlignment="Left" Margin="135,102,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.245,0.51"/>

    </Grid>





这是我的后端:





Here is my back end:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using Microsoft.Win32;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using BusinessModel;
using DataAccess;

namespace VinylCollection
{
    /// <summary>
    /// Interaction logic for ucAddVinyl.xaml
    /// </summary>
    public partial class ucAddVinyl : UserControl
    {
        public ucAddVinyl()
        {
            InitializeComponent();
        }


        #region Variable

        byte[] newImage;

        #endregion


        #region Methods

        public void InsertVinyl()
        {
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<VinylContext>());

            Vinyl vinyl = new Vinyl();



            vinyl.Name = tbName.Text;
            vinyl.VinylLabel = tbVinylLabel.Text;
            vinyl.Genre = tbGenre.Text;
            vinyl.SubGenre = tbSubGenre.Text;
            vinyl.Url = tbUrl.Text;
            vinyl.Photo = newImage;

            VinylContext contextVinyl = new VinylContext();
            contextVinyl.VinylSet.Add(vinyl);
            contextVinyl.SaveChanges();
        }

        public void OpenImage()
        {
            OpenFileDialog ofg = new OpenFileDialog();
            ofg.Title = "Select an image";
            ofg.Filter = "Images (.jpg, .png, .gif, .bmp)|*.jpg;*.png;*.gif;*.bmp";
            ofg.Multiselect = false;

            if (ofg.ShowDialog() == true)
            {
                if (ofg.FileName != null && ofg.FileName.Length > 0)
                {
                    ofg.OpenFile();
                    FileStream fs = new FileStream(ofg.FileName, FileMode.Open, FileAccess.Read);
                    lblImageUpload.Content = ByteImageConverter.ImageToByte(fs);

                    byte[] imgStr = Convert.FromBase64String(lblImageUpload.Content.ToString());
                    newImage = imgStr;
                    imgPreview.Source = ByteImageConverter.ByteToImage(imgStr);
                }
            }

        }


        #endregion


        #region Classes

        public class ByteImageConverter
        {
            public static ImageSource ByteToImage(byte[] imageData)
            {
                BitmapImage biImg = new BitmapImage();
                MemoryStream ms = new MemoryStream(imageData);
                biImg.BeginInit();
                biImg.StreamSource = ms;
                biImg.EndInit();

                ImageSource imgSrc = biImg as ImageSource;

                return imgSrc;
            }


            public static string ImageToByte(FileStream fs)
            {
                byte[] imgBytes = new byte[fs.Length];
                fs.Read(imgBytes, 0, Convert.ToInt32(fs.Length));
                string encodeData = Convert.ToBase64String(imgBytes, Base64FormattingOptions.InsertLineBreaks);

                return encodeData;
            }
        }

        #endregion


        #region Events

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            InsertVinyl();
        }

        private void btnUpload_Click(object sender, RoutedEventArgs e)
        {
            OpenImage();


        }


        #endregion

       

    }
}





所以一切正常,问题就出现了这些数据回来了,把它放到一些标签和图像中。



这是我的Xaml:





So this all works fine, the problem is getting that data back, and putting it into some labels and an image.

Here is my Xaml:

<Grid Margin="0,0,-149,-48">
        <TextBox x:Name="tbSearch" HorizontalAlignment="Left" Height="23" Margin="10,41,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="200"/>
        <Label x:Name="lblSearch" Content="Vinyl Search" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" FontSize="16" FontWeight="Bold"/>
        <Button x:Name="btnSearch" Content="Search" HorizontalAlignment="Left" Margin="215,41,0,0" VerticalAlignment="Top" Width="75" Click="btnSearch_Click"/>
        <ComboBox x:Name="cbVinylResults" HorizontalAlignment="Left" Margin="10,105,0,0" VerticalAlignment="Top" Width="200"/>
        <Label x:Name="lblVinylResults" Content="Vinyl Results" HorizontalAlignment="Left" Margin="10,69,0,0" VerticalAlignment="Top"/>
        <Label x:Name="lblName" Content="Name" HorizontalAlignment="Left" Margin="10,133,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.245,0.51"/>
        <Label x:Name="lblVinylLabel" Content="Vinyl Label" HorizontalAlignment="Left" Margin="10,164,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.245,0.51"/>
        <Label x:Name="lblGenre" Content="Genre" HorizontalAlignment="Left" Margin="10,195,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.245,0.51"/>
        <Label x:Name="lblSubGenre" Content="Sub Genre" HorizontalAlignment="Left" Margin="10,226,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.245,0.51"/>
        <Label x:Name="lblImageUpload" Visibility="Hidden" Content="Upload Image" HorizontalAlignment="Right" Margin="0,284,90,0" VerticalAlignment="Top" RenderTransformOrigin="0.245,0.51" Width="337"/>
        <Label x:Name="lblUrl" Content="Website" HorizontalAlignment="Left" Margin="10,257,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.245,0.51"/>
        <Image x:Name="imgPreview" HorizontalAlignment="Left" Height="115" Margin="123,164,0,0" VerticalAlignment="Top" Width="167"/>
        <Label x:Name="lblImage" Content="Image Preview" HorizontalAlignment="Left" Margin="123,133,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.245,0.51"/>

    </Grid>





I have no idea where to begin with getting the data back. The idea is to search for a file, and the search button will find all entries for that word in the data, then put them in the listbox. Then when you select an item, you can view the details in using the labels.



(UPDATE) I have added the code to bring back all entries, however, I am still unsure how to use the textbox to search for a specific name, and populate the listbox with the resulting name.





I have no idea where to begin with getting the data back. The idea is to search for a file, and the search button will find all entries for that word in the data, then put them in the listbox. Then when you select an item, you can view the details in using the labels.

(UPDATE) I have added the code to bring back all entries, however, I am still unsure how to use the textbox to search for a specific name, and populate the listbox with the resulting name.

public void GetVinyl()
        {

            using (var db = new VinylContext())
            {

                // Display all vinyl from the database

                var query = from b in db.VinylSet

                            orderby b.VinylId

                            select b;


                foreach (var item in query)
                {

                    cbVinylResults.Items.Add(item.Name);

                }

            }

        }







Also I need for the listbox item to be selected and then that names information is then populated into my labels.



I know it might be easier to use listview or a datagrid, but this is the way I have to do it.



Thank you...




Also I need for the listbox item to be selected and then that names information is then populated into my labels.

I know it might be easier to use listview or a datagrid, but this is the way I have to do it.

Thank you...

推荐答案

I’m not a WPF expert so I can’t give you working code, however I can tell you the approach to use here.



The view for a set of results should be a ListView, with the ItemTemplate set to whatever you want the display for an individual Vinyl to be (probably a panel of some kind with some text fields on it).



You should data bind that to a (notifying) property of type IList<Vinyl> (if your data’s big it might be some kind of virtual list, but a plain List is probably going to be fine for the implementation at this point) in your view model for the results view.



And when you search, you should get the result set from the data source (with a Linq query, I imagine) and assign it to the relevant property in the view model.
I'm not a WPF expert so I can't give you working code, however I can tell you the approach to use here.

The view for a set of results should be a ListView, with the ItemTemplate set to whatever you want the display for an individual Vinyl to be (probably a panel of some kind with some text fields on it).

You should data bind that to a (notifying) property of type IList<Vinyl> (if your data's big it might be some kind of virtual list, but a plain List is probably going to be fine for the implementation at this point) in your view model for the results view.

And when you search, you should get the result set from the data source (with a Linq query, I imagine) and assign it to the relevant property in the view model.


public void SearchVinyl()
       {
           SqlConnection conn;
           SqlCommand comm;
           SqlDataReader reader;
           string connectionString = VinylCollection.Properties.Settings.Default.DataAccess_VinylContextConnectionString;
           conn = new SqlConnection(connectionString);
           comm = new SqlCommand("SELECT Name, VinylLabel, Genre, SubGenre, Photo, Url FROM Vinyls WHERE Name=@Name", conn);
           conn.Open();
           comm.Parameters.AddWithValue("@Name", tbSearch.Text);
           reader = comm.ExecuteReader();
           while (reader.Read())
           {            
               lblName.Content = reader["Name"].ToString();
               lblVinylLabel.Content = reader["VinylLabel"].ToString();
               lblGenre.Content = reader["Genre"].ToString();
               lblSubGenre.Content = reader["SubGenre"].ToString();
               lblImageUpload.Content = reader["Photo"];
               lblUrl.Content = reader["Url"].ToString();
               byte[] img = Encoding.Unicode.GetBytes(lblImageUpload.Content.ToString());
               newImage = img;
               imgPreview.Source = ByteImageConverter.ByteToImage(img);

           }
           reader.Close();
           conn.Close();

           
      
       }


这篇关于C#WPF实体框架代码需要第一个帮助!请!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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