I am using Visual Studio 2012 C Sharp (C#) and SQL Server Express. I am trying to go through the MSDN Walkthrough: Display Data from a SQL Server Database in a DataGrid Control. I have added the recommended AdventureWorksLT2008 sample database. Here are the instructions I followed:
AdventureWorksModel.edmx
and then click Add. (The Entity Data Model Wizard appears.)App.Config
as check box is selected, and then click Next.To retrieve and present the data:
MainWindow.xaml
file.<Grid>
and </Grid>
tags to add a DataGrid named dataGrid1
.Window_Loaded
for the Loaded event.MainWindow.xaml.vb
or MainWindow.xaml.cs
) for the Window.Add the following code to retrieve only specific values from the joined tables and set the ItemsSource
property of the DataGrid to the results of the query:
using System;
using System.Collections.Generic;
using System.Data.Objects;
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.Windows.Navigation;
using System.Windows.Shapes;
namespace DataGridSQLExample
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
AdventureWorksLT2008Entities dataEntities = new AdventureWorksLT2008Entities();
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ObjectQuery<Product> products = dataEntities.Products;
var query =
from product in products
where product.Color == "Red"
orderby product.ListPrice
select new { product.Name, product.Color, CategoryName = product.ProductCategory.Name, product.ListPrice };
dataGrid1.ItemsSource = query.ToList();
}
}
}
When I run I get this error:
Cannot implicitly convert type 'System.Data.Entity.DbSet' to 'System.Data.Objects.ObjectQuery' on this line: ObjectQuery products = dataEntities.Products;
Nothing I have tried works - any suggestions?
You can use directly , you don't need to cast
var query =
from product in dataEntities.Products
where product.Color == "Red"
orderby product.ListPrice
select new { product.Name, product.Color, CategoryName = product.ProductCategory.Name, product.ListPrice };
Nota :
ObjectQuery represents a typical query that is executed on a conceptual model in the context of a given object.
dataEntities.Products represents set of datas
I realize this is really old but you could also do the following:
Change:
using System.Data.Objects;
To:
using System.Data.Entity;
and Change:
ObjectQuery<Product> products = dataEntities.Products;
To:
DbSet<Product> products = dataEntities.Products;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With