Does LINQ SELECT support System.Web.UI.AttributeCollection - linq

I'm trying to populate attributes collection in a LINQ SELECT query.
appointments.AddRange(db.Events.ToList().Select(appointment => new Appointment
{
ID = appointment.ID,
Subject = appointment.Subject,
Attributes["Location"] = appointment.Location
}));
Is this supported?
Thanks.

Related

How does one use .ToList() Inside of a Linq Query?

I've got a class that contains a list item. I would like for a linq query to populate the class, including this list. Here is my query:
var query = from c in context.Cars
select new CarListItem()
{
ID = c.ID,
Make = c.Make,
AvailableColors = context.CarColors.Where(u => u.CarID == c.ID).ToList()
};
Basically, I want to get a list of all of the cars, including a list of the available colors for each respective car.
The problem is that the inclusion of .ToList() within the query results in an error: An error occurred:
LINQ to Entities does not recognize the method 'System.Collections.Generic.List`1[CarSystem.Models.CarColors] ToList[CarColors](System.Collections.Generic.IEnumerable`1[CarSystem.Models.CarColors])' method, and this method cannot be translated into a store expression.
At this point, I don't know whether I am just using wrong syntax within the Linq query (should I use something other than .ToList()?) or if maybe the architecture of the models is wrong.
You can't. EF tries to translate ToList() to SQL and doesn't know how.
You could project to another type, then call ToList():
var query = (from c in context.Cars
select new
{
ID = c.ID,
Make = c.Make,
AvailableColors = context.CarColors.Where(u => u.CarID == c.ID)
}).ToList()
.Select(c => new CarListItem()
{
ID = c.ID,
Make = c.Make,
AvailableColors = c.AvailableColors.ToList()
});
or change the type of CarListItem.AvailableColors to IEnumerable<CarColor>:
var query = from c in context.Cars
select new CarListItem()
{
ID = c.ID,
Make = c.Make,
AvailableColors = context.CarColors.Where(u => u.CarID == c.ID)
};

How to add/edit DataServiceQuery LINQ Projections in Silverlight?

Silverlight 5 / WCF Data Services 5.6.0 / Entity Framework 5 / Asynchronous LINQ DataServiceQuery
How can I reset/delete/uncache/remove the projections from my DataServiceQuery LINQ query in subsequent executions ?
Consider the below code:
var query =
(
from c in context.Customers
select new Customers()
{
ID = c.ID,
Name = c.Name,
}
) as DataServiceQuery<Customers>;
query.BeginExecute((result) =>
Dispatcher.BeginInvoke(() =>
{
// process results from query...
// query.EndExecute(result).ToList();
}), null);
In the above snippet, I'm creating a LINQ query with two projections (columns) which will return the ID and Name fields via WCF Data Services. This works fine; issue starts below...
In another method which executes later, I have a similar query to fetch additional columns/projections. However, the below LINQ query returns the same resultset as above and ignores the additional columns:
var query =
(
from c in context.Customers
select new Customers()
{
ID = c.ID,
Name = c.Name,
Age = c.Age, // additional columns returning null
Height = c.Height // additional columns returning null
}
) as DataServiceQuery<Customers>;
query.BeginExecute((result) =>
Dispatcher.BeginInvoke(() =>
{
// process results from query...
// query.EndExecute(result).ToList();
}), null);
Removing all projections to return all columns fails too; I just get back the initial ID and Name fields specified earlier:
var query =
(
// No projections, just get ALL columns please!
from c in context.Customers
select c
) as DataServiceQuery<Customers>;
query.BeginExecute((result) =>
Dispatcher.BeginInvoke(() =>
{
// process results from query...
// query.EndExecute(result).ToList();
}), null);
How can I get the DataServiceQuery object to discard the previously specified projections? I don't have the option to execute the query which returns all columns first.
Issue resolved: Before executing any LINQ query, set the below MergeOption on the WCF Data Service context:
context.MergeOption = MergeOption.OverwriteChanges;
Related info:
http://social.msdn.microsoft.com/Forums/silverlight/en-US/f36d2643-661e-4048-88cf-a38df36a0b1a/linq-expand-and-dataservicequery
WCF Data Service and Silverlight: DataServiceQuery<T> will not re-perform query

How to Query CRM 2011 EntityCollection in LINQ

I am trying to query a EntityCollection / PartyList using LINQs and have had no luck figuring out how to do it.
My query is:
var linqQuery = (from r in gServiceContext.CreateQuery("campaignresponse")
select new
{
activityid = !r.Contains("activityid") ? string.Empty : r["activityid"],
CustomerId = !r.Contains("customer") ? string.Empty : r["customer"]
});
CustomerId is the PartyList / EntityCollection. If I run that code I get, Microsoft.Xrm.Sdk.EntityCollection instead of my actual data. Any ideas on how to query the EntityCollection in LINQ and return the data? Thanks!
The EntityCollection has the property Entities which contains the retrieved data.
EntityCollection.Entities
Edit:
So for example:
var result = service.RetrieveMultiple(query).Entities
.Select(e =>
new
{
firstname = e.Attributes["firstname"],
lastname = e.Attributes["lastname"]
});

The best way to get read only data using EF and support sporting/searching/filtering

Lets say that I need to execute this query with EF in business layer
var list = context.Invoices.Select(x => new
{
InvoiceNumber = x.InvoiceNUmber,
InvoiceDate = x.InvoiceDate,
CustomerName = x.Customer.CustomerName,
TotalValue = x.InvoiceData.Sum(y => y.Quantity * y.Price),
Id = x.Id
}).ToList();
What can I do for this list to be easily sortable, searchable or filterable in UI layer?
Thanks,
Goran
The way to do it is to return a object that is not anonymous. That is, create a class to hold this data. It should either have an implicit zero-argument constructor (because you have no constructors), or an explicit zero-argument one (because you have defined other constructors). Then you can say:
List<MyObject> list = context.Invoices.Select(x => new MyObject()
{
InvoiceNumber = x.InvoiceNUmber,
InvoiceDate = x.InvoiceDate,
CustomerName = x.Customer.CustomerName,
TotalValue = x.InvoiceData.Sum(y => y.Quantity * y.Price),
Id = x.Id
}).ToList();
Now you can return the strongly-typed list of objects out of your business layer, and your UI layer can use LINQ (or whatever) to do sorting/filtering/paging.

Set and return object with LINQ

I have a MVC 2 project, using Entity Framework, in Visual Studio 2010 and I have a class 'ProductModel' which is doing a LINQ query to return an product from the database.
I want to return Products objects instead of the default "entities" query objects so I founded that I had to do like this:
var product = from x in productosBD.Products
where x.Id == id
select new ProductoModels { Id = x.Id, NombreCorto = x.NombreCorto, NombreLargo = x.NombreLargo, Pvp = x.Pvp .... };
The problem is that I have to do ALL the assignations with all the attributes of the database table (could be 30 easily) So my question is : Is there any way to do a mapping of the database entities with my objects class automatically? Something like:
var product = from xin productosBD.Products
where x.Id == id
select x;
but retorning a Products object?
Thanks in advance
Automapper : http://automapper.codeplex.com/
http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/01/22/automapper-the-object-object-mapper.aspx
public static void Configure() {
Mapper.CreateMap<Order, OrderViewModel>();
Mapper.CreateMap<OrderLineItem, OrderLineItemViewModel>();
}
var viewModel = Mapper.Map<Order, OrderViewModel>(order);

Resources