将linq转换为强类型的ObservableCollection的实体查询的最佳方法 [英] Best way for converting linq to entity query to strongly typed ObservableCollection

查看:160
本文介绍了将linq转换为强类型的ObservableCollection的实体查询的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些天我正在学习Entity Framework 5. 我开发基于MVVM和PRISM的WPF应用程序. 为了获取属性更改通知,我使用ObservableCollection保留数据.

I am learning these days Entity Framework 5. I developing WPF application which based on MVVM and PRISM. In order to get property changed notifications I am using ObservableCollection for keep my data.

当我使用linq进行实体投影时遇到问题,我不确定什么是最好的解决方案.

I have problem when I use linq to entity projection and I am not sure what is the best solution for it.

如您所知,当您通过linq对实体执行投影时,您将获得匿名类型,而没人知道该方法的范围.我搜索了如何使此查询成为强类型.

As you know, when you execute projection through linq to entity you get anonymous type that no one know out the scope of the method. I searched how to make this query strongly typed.

我看到了有关此问题的一些讨论,但找不到最佳方法.

I seen some discussions about this issue but I couldn`t find what is the best approach.

我看到了3种不同的解决方案:

I seen 3 different solutions:

  1. 使用QueryView
  2. 使用定义查询
  3. http://social.msdn.microsoft.com/Forums/zh-CN/adodotnetentityframework/thread/c6b8375a-2684-4020-bbcc-24433baf997b

数字3是最简单的数字,看起来与我所需要的完全一样,但是我知道反射是高成本"操作,因此让我回到了问题所在:什么是解决此问题的最佳方法?还有其他解决方案吗?

Number 3 is the simplest one and seen like exactly what I need but I know that Reflection is "high cost" operation so it return me to the question what is the best approach for this problem? any other solutions?

推荐答案

您不应投影到匿名类型,而应投影到命名类型.

You should not project to an anonymous type but to named type.

var query = from c in Customers 
            join o in Orders on c.CustomerID equals o.CustomerID
            select new OrderDto {
                                    customer_name = c.CompanyName,
                                    order_date = o.OrderDate,
                                    order_Id = o.OrderID
                                };

使用简单的类OrderDto.所以那不是您的选择.

Which uses a simple class OrderDto. So that's none of your options.

旁注:您可能可以使用导航属性:

Side note: you can probably use navigation properties:

var query = from o in Orders
            select new OrderDto {
                                    customer_name = o.Customer.CompanyName,
                                    order_date = o.OrderDate,
                                    order_Id = o.OrderID
                                };

和EF将弄清楚如何加入.

and EF will figure out how to join.

这篇关于将linq转换为强类型的ObservableCollection的实体查询的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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