Am I doing it wrong ir it is not possible to project a certain data model to strongly typed model instead of anonymous object?
I have this Linq expression:
var kudosLogsQuery = _kudosLogsDbSet
.Include(log => log.Type)
.Include(log => log.Employee)
.Where(log =>
log.OrganizationId == options.OrganizationId &&
log.BasketId == null)
.Where(StatusFilter(options.Status))
.Where(TypeFilter(options.TypeId))
.Where(UserFilter(options.SearchUserId))
.Select(log => new Comment
{
Id = log.Id,
Created = log.Created,
Employee = new Employee
{
FirstName = log.Employee.Name
}
Type = new Type
{
Name = log.Type.Name
}
})
.OrderByDescending(log => log.Created)
.ToList()
TypeFilter, StatusFilter, UserFilter is either x => true or just an another filter by Status, Type or User.
Unfortunately it produces an SQL statement that takes all fields from that table and projects it on the application side. The conclusion was made by testing these Linq expressions on SQL profiler.
Question:
Am I doing something wrong, or SQL projection works with anonymous objects only?
Thanks
Related
I am using MVC 4 and entity framework, I am retrieving emails from the server:
var data = db.Candidates.Where(c => ids.Contains(c.ID) && c.Email1 != null).Select(c => new { c.Email1, c.ID }).ToList();
My first question: Does LINQ allow me to return an empty string form the Email1 field if it is null, similar to SQL coalesce? (I would remove the null test from the where clause).
2nd question: what would be the easiest object to use (to replace the "var data =" if I wanted to get c.Name along with the Email1, then use both in a loop? Should I create a model for just 2 fields?
Thanks so much in advance for any insights.
My first question: Does LINQ allow me to return an empty string form the Email1 field if it is null, similar to SQL coalesce? (I would remove the null test from the where clause).
Yes, there is the ?? operator that works similar to the coalesce.:
new { Email1 = c.Email1 ?? "", c.ID } //String.Empty would be nicer, but i think it depends on EF version if you are allowed to use it.
For your second question, if this is the only place you are going to use them, then anonymous is pretty fine.
If you want to use this on other places, yes create an object just with two properties... That's the object's purpose after all. (or maybe a struct?)
Ask one question at a time.
2a. The Null Coalescence operator in C# is ??.
2b. This may or may not be converted by your Linq Provider into a database query.
Do it like this,
var data = db.Candidates
.Where(c => ids.Contains(c.ID))
.Select(c => new
{
Id = c.Id,
Email1 = c.Email1 ?? string.Empty,
Name = c.Name
});
foreach(var row in data)
{
var name = row.Name // etc...
}
If your Linq Provider does not support the ?? operator, put in a .ToList() and use linq-to-objects to perform the tranformation like this,
var data = db.Candidates
.Where(c => ids.Contains(c.ID))
.ToList() // <-- from here is Linq-To-Objects
.Select(c => new
{
Id = c.Id,
Email1 = c.Email1 ?? string.Empty,
Name = c.Name
});
I have a database where I'm wanting to return a list of Clients.
These clients have a list of FamilyNames.
I started with this
var query = DbContext.Clients.Include(c => c.FamilyNames).ToList() //returns all clients, including their FamilyNames...Great.
But I want somebody to be able to search for a FamilyName, ifany results are returned, then show the clients to the user.
so I did this...
var query = DbContext.Clients.Include(c => c.FamilyNames.Where(fn => fn.familyName == textEnteredByUser)).ToList();
I tried...
var query = DbContext.Clients.Include(c => c.FamilyNames.Any(fn => fn.familyName == textEnteredByUser)).ToList();
and...
var query = DbContext.FamilyNames.Include(c => c.Clients).where(fn => fn.familyname == textEnteredByUser.Select(c => c.Clients)).ToList();
What I would like to know (obviously!) is how I could get this to work, but I would like it if at all possible to be done in one query to the database. Even if somebody can point me in the correct direction.
Kind regards
In Linq to Entities you can navigate on properties and they will be transformed to join statements.
This will return a list of clients.
var query = DbContext.Clients.Where(c => c.FamilyNames.Any(fn => fn == textEnteredByUser)).ToList();
If you want to include all their family names with eager loading, this should work:
var query = DbContext.Clients.Where(c => c.FamilyNames.Any(fn => fn == textEnteredByUser)).Include(c => c.FamilyNames).ToList();
Here is some reference about loading related entities if something doesn't work as expected.
You can use 'Projection', basically you select just the fields you want from any level into a new object, possibly anonymous.
var query = DbContext.Clients
.Where(c => c.FamilyNames.Any(fn => fn == textEnteredByUser))
// only calls that can be converted to SQL safely here
.Select(c => new {
ClientName = c.Name,
FamilyNames = c.FamilyNames
})
// force the query to be materialized so we can safely do other transforms
.ToList()
// convert the anon class to what we need
.Select(anon => new ClientViewModel() {
ClientName = anon.ClientName,
// convert IEnumerable<string> to List<string>
FamilyNames = anon.FamilyNames.ToList()
});
That creates an anonymous class with just those two properties, then forces the query to run, then performs a 2nd projection into a ViewModel class.
Usually I would be selecting into a ViewModel for passing to the UI, limiting it to just the bare minimum number of fields that the UI needs. Your needs may vary.
I'm writing an ASP.NET Web Pages application and in it, I have a massive LINQ to Entities query. This query pulls data from a table in the database, filters it, groups the data twice, and adds extra properties to the result set. I then loop through the table, outputting the rows.
The query is quite big, sorry:
accountOrders = db.EventOrders
.Where(order => order.EventID == eventID)
.OrderBy(order => order.ProductCode)
.GroupBy(order => new { order.AccountNum, order.Exhibitor, order.Booth })
.Select(orders =>
new {
Key = orders.Key,
ProductOrders = orders
.GroupBy(order => new { order.ProductCode, order.Product, order.Price })
.Select(productOrders =>
new {
Key = productOrders.Key,
Quantity = productOrders.Sum(item => item.Quantity),
HtmlID = String.Join(",", productOrders.Select(o => (o.OrderNum + "-" + o.OrderLine))),
AssignedLines = productOrders.SelectMany(order => order.LineAssignments)
})
})
.Select(account =>
new {
Key = account.Key,
// Property to see whether a booth number should be displayed
HasBooth = !String.IsNullOrWhiteSpace(account.Key.Booth),
HasAssignedDigitalLines = account.ProductOrders.Any(order => order.AssignedLines.Any(line => line.Type == "digital")),
// Dividing the orders into their respective product group
PhoneOrders = account.ProductOrders.Where(prod => ProductCodes.PHONE_CODES.Contains(prod.Key.ProductCode)),
InternetOrders = account.ProductOrders.Where(prod => ProductCodes.INTERNET_CODES.Contains(prod.Key.ProductCode)),
AdditionalOrders = account.ProductOrders.Where(prod => ProductCodes.ADDITIONAL_CODES.Contains(prod.Key.ProductCode))
})
.ToList();
I use the added properties to help style the output. For example, I use HasBooth property to check whether or not I should output the booth location in brackets beside the exhibitor name. The problem is I have to save this big query as an IEnumerable, meaning I get the error: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. Should I even be manipulating the query this way?
Any advice is much appreciated!
At some point, you are passing in a dynamic datatype to the method, which in turn changes the return type to simply dynamic. You can either cast the dynamic type to a type that is recognised at compile time or explicitly set the return type instead of using var.
You can read more about this issue here: http://www.mikesdotnetting.com/Article/198/Cannot-use-a-lambda-expression-as-an-argument-to-a-dynamically-dispatched-operation
This problem related to LINQ-to-entity.
I posted a similar question but it got confusing without an answer, so I am providing an example and a new shout for help.
I have a class "Colors" containing an ObservableCollection which has two members, Index and Name and populated like :
0 - Red
1 - Blue
2 - Green
and I have a database table containing a list of integers of my favorite colors. I would like to return a query with both the integer value of my favorite color and also the matching name (returned by the observablecollection) based on the index value stored in the database.
This statement in isolation works fine and returns my color name :-
string ColorName = Colors.Names.Where(x => x.Index == 1).FirstOrDefault().Name;
but when included within the LINQ-to-entity query :-
var query = from c in context.FavoriteColor
select (new Item
{
Id = c.Id,
ColorName = Colors.Names.Where(x => x.Index == c.ColorIndex).FirstOrDefault().Name
});
I get this error :
Unable to create a constant value of type 'blah blah'. Only primitive
types ('such as Int32, String, and Guid') are supported in this
context.
I understand that maybe the object is being returned within the LINQ statement but I thought by specifying the .Name notation on the end, which is a string member, it would use that and assign it to "ColorName", alas not.
Have you tried:
var query = from c in context.FavoriteColor
select new { c.Id, c.ColorIndex };
var result = from c in query.ToList()
select new Item
{
Id = c.Id,
ColorName = Colors.Names.Where(x => x.Index == c.ColorIndex).FirstOrDefault().Name
};
You are trying to use a CLR object in a database query. LINQ-to-Entities is saying you can't do that. Get the color name after the query has completed.
var dbItems = context.FavoriteColor.Select(c => new {
c.Id,
c.ColorIndex
).ToList();
var items = dbItems.Select(item => new Item {
Id = item.Id,
ColorName = Colors.Names.Where(x => x.Index == item.ColorIndex).First().Name
})
The idea here is that the call to ToList hits the database and returns the results in a CLR object. That object can then be used like any other object.
So I am trying to order a query by an int var that is in an ordered list of the same int vars; e.g. the query must be sorted by the lists order of items. Each datacontext is from a different database which is the reason i'm making the first query into an ordered list of id's based on pet name order, only the pet id is available from the second query's data fields, Query looks like:
using (ListDataContext syndb = new ListDataContext())
{
using (QueryDataContext ledb = new QueryDataContext())
{
// Set the order of pets by name and make a list of the pet id's
var stp = syndb.StoredPets.OrderBy(x => x.Name).Select(x => x.PetID).ToList();
// Reorder the SoldPets query using the ordered list of pet id's
var slp = ledb.SoldPets.OrderBy(x => stp.IndexOf(x.petId)).Select(x => x);
// do something with the query
}
}
The second query is giving me a "Method 'Int32 IndexOf(Int32)' has no supported translation to SQL." error, is there a way to do what I need?
LINQ to SQL (EF) has to translate your LINQ queries into SQL that can be executed against a SQL server. What the error is trying to say, is that the .NET method of IndexOf doesn't have a SQL equivalent. You may be best to get your data from your SoldPets table without doing the IndexOf part and then doing any remaining ordering away from LINQ to SQL (EF).
Something like this should work:
List<StoredPet> storedPets;
List<SoldPet> soldPets;
using (ListDataContext listDataContext = new ListDataContext())
{
using (QueryDataContext queryDataContext= new QueryDataContext())
{
storedPets =
listDataContext.StoredPets
.OrderBy(sp => sp.Name)
.Select(sp => sp.PetId)
.ToList();
soldPets =
queryDataContext.SoldPets
.ToList();
}
}
List<SoldPets> orderedSoldPets =
soldPets.OrderBy(sp => storedPets.IndexOf(sp.PetId))
Note: Your capitalisation of PetId changes in your example, so you may wish to look at that.
LinqToSql can't transalte your linq statement into SQL because there is no equivalent of IndexOf() method. You will have to execute the linq statement first with ToList() method and then do sorting in memory.
using (ListDataContext syndb = new ListDataContext())
using (QueryDataContext ledb = new QueryDataContext())
{
var stp = syndb.StoredPets.OrderBy(x => x.Name).Select(x => x.PetID).ToList();
// Reorder the SoldPets query using the ordered list of pet id's
var slp = ledb.SoldPets.ToList().OrderBy(x => stp.IndexOf(x.petId));
}
You can use this, if the list size is acceptable:
using (ListDataContext syndb = new ListDataContext())
{
using (QueryDataContext ledb = new QueryDataContext())
{
var stp = syndb.StoredPets.OrderBy(x => x.Name).Select(x => x.PetID).ToList();
var slp = ledb.SoldPets.ToList().OrderBy(x => stp.IndexOf(x.petId));
// do something with the query
}
}