Click here to Skip to main content
15,868,141 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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:
C#
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; }
    }

}


Here is my DataAccess:
XML
public class VinylContext : DbContext
    {
        public DbSet<Vinyl> VinylSet { get; set; }
    }


Here is my Xaml for adding an entry:
XML
<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:

C#
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

       

    }
}


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:

XML
<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.

C#
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...
Posted
Updated 21-Jun-13 15:00pm
v3
Comments
johannesnestler 21-Jun-13 5:39am    
You are using WPF and EF with POCO classes - so best use is just binding of the found (corresponding to file) Vinyl objects (maybe implement INotifyPropertyChanged Interface...) . But this should be obviouse when following such a book - there is a reason you want to have code first... So you have any specifc problems in setting the binding up? (in your last xaml listing) or is it the code to find the corresponding entries in the database after file was selected?
TeacherDean 21-Jun-13 7:19am    
I am just learning new technologies, so I am unsure how to retrieve the data and use it. Because my textbook only covered Code First's creation and customization of database, not the implementation of it, within a WPF or any other app.

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.
 
Share this answer
 
Comments
johannesnestler 21-Jun-13 6:34am    
good advice - I'd do something similar
C#
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();

           
      
       }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900