问题
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.
I have problem when I use linq to entity projection and I am not sure what is the best solution for it.
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.
I seen 3 different solutions:
- using QueryView
- using Define Query
- http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/c6b8375a-2684-4020-bbcc-24433baf997b
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?
回答1:
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
};
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
};
and EF will figure out how to join.
回答2:
This is what I use:
I use VB:
Dim ObjectQuery As IQueryable(Of YourObject) = CType((From c In YourContext.objects Select c), IQueryable(Of YourObject))
Return New ObservableCollection(Of YourObject)(ObjectQuery)
a simple version of the above based on a client table in C# without the CType. I used a vb to C# converter so it might need to be adjusted
IQueryable<client> ClientQuery = from c in ftcContext.clients select c;
return new ObservableCollection<client>(ClientQuery);
来源:https://stackoverflow.com/questions/15353579/best-way-for-converting-linq-to-entity-query-to-strongly-typed-observablecollect