C#中的数据类型转换错误

data type conversion error in C#

我想使用 C# 在数据网格中显示存储在 SQL 服务器数据库中的数据。我试着按照this examples on msdn,但是遇到了类型转换错误。我正在使用 Visual studio 2013.

我连接到 SQL 服务器,并创建了一个名为 myEntity 的 ado.net 数据模型。该模型包含几个表,其中一个,剧院,是我尝试在屏幕上显示的内容。

这是我的资料: 在 MainWindow.xaml 文件中我有

<Page x:Class="XYZ.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="theater List" Height="350" Width="525"
        Loaded="Data_Loaded">
    <Grid>
        <DataGrid Name="dataGrid1"></DataGrid>
    </Grid>
</Page>

在 MainWindow.xaml.cs 文件中我有:

using System.Data.Entity.Core.Objects;
using System.Windows;
using System.Windows.Controls;
using System.Linq;

namespace XYZ
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public sealed partial class MainPage : Page
    {
        myEntities dataEntites = new myEntities();

        public MainPage()
        {
            InitializeComponent();
        }

        private void Data_Loaded(object sender, RoutedEventArgs e)
        {
                ObjectQuery<Theater> theaters = dataEntites.Theaters;

                var query = from theater in theaters
                            where theater.type == "Big"
                            orderby theater.id
                            select new
                            {
                                theater.State,
                                theater.City,
                                theater.Type, 
                                theater.Id, 
                                theater.Name,
                                theater.Capacity
                                 ...
                            };

                dataGrid1.ItemsSource = query.ToList();  
        }
    }
}

我在线上遇到错误信息

ObjectQuery<Theater> theaters = dataEntites.Theaters;

其中指出:

Cannot implicitly convert type 'System.Data.Entity.DbSet<XYZ.Theater>' to 'System.Data.Entity.Core.Objects.ObjectQuery<XYZ.Theater>'

我该如何解决这个问题?谢谢。

这里的问题是 System.Data.Entity.Core.Objects.ObjectQuery<T> 没有从 System.Data.Entity.DbSet<T> 继承,因此一个 class 的对象不能隐式转换为另一个(预计 implicit type conversion operator 会被覆盖,但事实并非如此。

因此您只需将变量剧院的类型从 ObjectQuery<Theater> 更改为 DbSet<Theater>:

                DbSet<Theater> theaters = dataEntites.Theaters;

                var query = from theater in theaters 
                        where theater.type == "Big"
                        orderby theater.id
                        select new
                        {
                            theater.State,
                            theater.City,
                            theater.Type, 
                            theater.Id, 
                            theater.Name,
                            theater.Capacity
                             ...
                        };