I'm trying to get rows based on a WHERE clause in a DbSet object. I have this:
dbContext.Workers
I can get a list like this:
workers = m.Workers.Where(w => w.BranchId == curUser.BranchId).ToList<Worker>();
But as you can see, it returns a List<Worker> and I can't use methods like workers.Find(WorkerId) with it.
Basically, I'm trying to return a DBSet based on some filter I mean I want to use LINQ on a DBSet class. I want this because I need to use workers.Find(WorkerId) also maybe I will need to update this model. So, I will get a list based on where clause, I will change some values and will use dbContext.SaveChanges(). Is that possible?
Thanks
Where(...) returns an IQueryable, which you can manipulate BEFORE the query runs. ToList() will force execution of the query and put the objects into memory. If you want to 'find' an item AFTER the query then you could do something like this with your List:
workers.SingleOrDerfault(x => x.WorkerId == WorkerId);
If you have them all in memory like this, and make changes, then you will persist those changes with a call to .SaveChanges().
However, if you need to apply more filtering to your IQueryable BEFORE the query hits the database, then you'll want to manipulate the IQueryable BEFORE the call to ToList().
Related
I am very new with C# and need some help. I am working on someone elses code and they are pulling data from a Model. I am trying to join two tables and need to use Include but the error is '==' cannot be applied to Guid and IQueryable. Could someone help with this please. Thanks in advance!
Yes, I am.
.Where() represents your filter. .Select() represents what you want back. If you just want the entities back you don't need a .Select().
If you have an association between menu items and MenuItemProgramData, for example, a MenuItem holds a reference to a MenuItemProgramData then you don't even need the first ID select statement:
return context.DbMenuItems
.Where(x => x.MenItemsProgramData.Plu == plu);
Note: If your context defines DbSet<T> for your various top level entities, you can just use context.Ts rather than .GetItems<T>.
If the relationship exists then this is the preferred approach. Let SQL do the work. The consumer of your method can further .Select() the applicable data, sort it, paginate it, and even append .Include() if you do want to interact with the entire entity graph.
If you don't have a relationship between the menu item and that program data, and know that the # of item IDs from the first query will remain relatively small (say, sub-100) then:
var itemIds = context.DbMenuItemProgramDatas
.Where(x => x.Plu == plu)
.Select(x => x.MenuItemId)
.ToList();
Without the .ToList() you are dealing with an IQueryable which EF would potentially still attempt to translate to SQL statements when later consumed. By using .ToList() it will execute the SQL and populate a List<int>. (Assuming the menu item ID is an int)
To get the IQueryable menu item data rows:
return context.DbMenuItems
.Where(x => itemIds.Contains(x.Id));
And that is it.
Edit: Based on the comment "I want to return a field named ParentId to know if it is empty or not. That's all but I need both tables linked to get that answer."
Additionally, looking back at the original code, the naming of the method is a bit misleading. GetItemProgramDataForSubItems implies returning MenuItemsProgramData rather than MenuItems... However, if ParentId is a property of MenuItem, then the caller of this method can use:
var hasParentId = context.GetItemProgramDataForSubItems(plu)
.Any(x => x.ParentId.HasValue);
If the ParentId is on the MenuItemsProgramData:
var hasParentId = context.GetItemProgramDataForSubItems(plu)
.Any(x => x.MenuItemsProgramData.ParentId.HasValue);
Beyond that, you may want to elaborate on what your entities and relationships look like, and what exactly you aim to accomplish from your method or business logic.
I'm running an EF statement where I need to calculate de deductibles. After long trying, I can't seem to add a custom function in a .Select() statement. Instead I'm trying to add the values after my .Select() statement.
The problem here is, in my CalculateDeductibles() I can't seem to add any values to item.Deductibles.
The GetDeductibles(item.RequestId) is a rather heavy funtion that does several extra queries, so I'm trying to prevent to convert my IQueryable to an IList object.
So there are actually 2 questions:
Can I have the GetDeductibles() function directly in my .Select() statement?
Can I somehow (with keeping an eye on performance) add the value after I did my .Select()
Code:
public IQueryable<ReinsuranceSlip> GetReinsuranceSlipsOverview(int userId, int companyId, string owner, string ownerCompany)
{
IQueryable<ReinsuranceSlip> model = null;
model = _context.Request
.Where(w => w.RequestGroup.ProgramData.MCContactId == userId)
.Select(x => new ReinsuranceSlip()
{
Id = x.Id,
RequestId = x.Id,
LocalPolicyNumber = x.LocalPolicyNumber,
BusinessLine = x.RequestGroup.ProgramData.BusinessLine.DisplayName,
BusinessLineId = x.RequestGroup.ProgramData.BusinessLine.Id,
ParentBroker = x.RequestGroup.ProgramData.Broker.Name,
LocalBroker = x.Broker.Name,
InceptionDate = x.InceptionDate,
RenewDate = x.RenewDate,
//Deductibles = CalculateDeductibles(x)
});
CalculateDeductibles(model);
return model;
}
private void CalculateDeductibles(IQueryable<ReinsuranceSlip> model)
{
//model.ForEach(m => m.Deductibles = GetDeductibles(m.RequestId));
foreach (var item in model)
{
item.Deductibles = GetDeductibles(item.RequestId);
}
}
Updated and Sorry for the first version of this answer. I didn't quite understand.
Answer 1: IQueryable is using to creating a complete SQL statement to call in SQL Server. So If you want to use IQueryable, your methods need to generate statements and return it. Your GetDetuctibles method get request Id argument but your queryable model object didn't collect any data from DB yet, and it didn't know x.Id value. Even more, your GetCarearDetuctiples get an argument so and with that argument generates a queryable object and after some calculations, it returns decimal. I mean yes you can use your methods in select statement but it's really complicated. You can use AsExpendable() LINQ method and re-write your methods return type Expression or Iqueryable.
For detailed info you should check. This:
Entity Navigation Property IQueryable cannot be translated into a store expression and this: http://www.albahari.com/nutshell/predicatebuilder.aspx
And you also should check this article to understand IQueryable interface: https://samueleresca.net/2015/03/the-difference-between-iqueryable-and-ienumerable/
Answer 2: You can use the IEnumerable interface instead IQueryable interface to achieve this. It will be easy to use in this case. You can make performance tests and improve your methods by time.
But if I were you, I'd consider using Stored Procedures for performance gain.
You'll have to understand the differences between an IEnumerable and an IQueryable.
An IEnumerable object holds everything to enumerate over the elements in the sequence that this object represents. You can ask for the first element, and once you've got it, you can repeatedly ask for the next element until there is no more next element.
An IQueryable works differently. An IQueryable holds an Expression and a Provider. The Expression is a generic description of what data should be selected. The Provider knows who has to execute the query (usually a database), and it knows how to translate the Expression into a format that the Provider understands.
There are two types of LINQ functions: the ones that return IQueryable<TResult> and the ones that return TResult. Functions form the first type do not execute the query, they will only change the expression. They use deferred execution. Functions of the second group will execute the query.
When the query must be executed, the Provider takes the Expression and tries to translate it into the format that the process that executes the query understand. If this process is a relational database management system this will usually be SQL.
This translation is the reason that you can't add your own functionality: the Expression must be translatable to SQL, and the only thing that your functions may do is call functions that will change the Expression to something that can be translated into SQL.
In fact, even entity framework does not support all LINQ functionalities. There is a list of Supported and Unsupported LINQ methods
Back to your questions
Can I have GetDeductibles directly in my query?
No you can't, unless you can make it thus simple that it will only change the Expression using only supporte LINQ methods. You'll have to write this in the format of an extension function. See extension methods demystified
Your GetDeductibles should have an IQueryable<TSource> as input, and return an IQueryable<TResult> as output:
static class QueryableExtensions
{
public static IQueryable<TResult> ToDeductibles<TSource, TResult, ...>(
this IQueryable<TSource> source,
... other input parameters, keySelectors, resultSelectors, etc)
{
IQueryable<TResult> result = source... // use only supported LINQ methods
return result;
}
}
If you really need to call other local functions, consider calling AsEnumerable just before calling the local functions. The advantage above ToList is that smart IQueryable providers, like the one in Entity Framework will not fetch all items but the items per page. So if you only need a few ones, you won't have transported all data to your local process. Make sure you throw away all data you don't need anymore before calling AsEnumerable, thus limiting the amount of transported data.
Can I somehow add the value after I did my .Select()
LINQ is meant to query data, not to change it. Before you can change the data you'll have to materialize it before changing it. In case of a database query, this means that you have a copy of the archived data, not the original. So if you make changes, you'll change the copies, not the originals.
When using entity framework, you'll have to fetch every item that you want to update / remove. Make sure you do not select values, but select the original items.
NOT:
var schoolToUpdate = schoolDbContext.Schools.Where(schoolId = 10)
.Select(school = new
{
... // you get a copy of the values: fast, but not suitable for updates
})
.FirstOrDefault();
BUT:
School schoolToUpdate = schoolDbContext.Schools.Where(schoolId = 10)
.FirstOrDefault()
Now your DbContext has the original School in its ChangeTracker. If you change the SchoolToUpdate, and call SaveChanges, your SchoolToUpdate is compared with the original School, to check if the School must be updated.
If you want, you can bypass this mechanism, by Attaching a new School directly to the ChangeTracker, or call a Stored procedure.
Whenever we want to use IEnumerable extension methods instead IQueryable version, we have use AsEnumerable() method.
var list = context.Details.AsEnumerable().Where(x => x.Code == "A1").ToList();
Why DbSet used IQueryable version of methods Like(Where , Select ,...) by default when other version available?
You'd usually want to use the IQueryable form, so that the filtering is done on the database instead of locally.
The code you've got will pull all records down to the client, and filter them there - that's extremely inefficient. You should only use AsEnumerable() when you're trying to do something that can't be performed in the database - usually after providing a server-side filter. (You may be able to do a coarse filter on the server, then a more fine-grained filter locally - but at least then you're not pulling all the records...)
Because IQuaryable methods are translated into SQL by Entity Framework.But IEnumerable method are not.So if you use IEnumearable all the data will be fetched from DB which is not always what you want.
i have the following LINQ statement:
var query =(from item in _itemRepository.FindAll()
where item.Id == "20649458"
from singelitem in item.ListOfChildren
where singelitem.Property == "singelitem"
from manyitems in item.ListOfChildren
where manyitems.Property == "many"
select new
{
item.Id,
singelitem,
manyitems
});
var result = query.ToList();
Tasks is a collection of objects and the where clause tasks.Property == "something" matches several items in the collection, but when i use a anonymous type in the select, i only get back one item (the first) of the matching results instead of a collection of Tasks. How can i get back all the matching tasks in a collection?
Edit:
What really happends is that i get flat objects, (just like a db result set from a join statement).
When you don't use anonymous type you're dealing with entity class which lazy loads the tasks when you access them. If you want to load tasks with your results try using Include method to eager load children. See How do you construct a LINQ to Entities query to load child objects directly, instead of calling a Reference property or Load()
This is the proper behavior of Linq. In fact what you are expecting is not possible. You are expecting a single item matching item.Id == "123"; and what if more than one? it just creates an anonymous item for each matched item. Just think of changing the first "from" statement with the second one; what would you expect?
Also, there is no relationship between first "from" statement and the second one which makes this query a bit "strange". Why not just splitting the query into 2; and creating a new object with the desired properties?
1) I wish to clarify some doubts on collections.
SampleDBDataContext PersonDB = new SampleDBDataContext("");
Table<Person> p=PersonDB.GetTable<Person>();
IEnumerable<Person> per = PersonDB.GetTable<Person>();
IQueryable<Person> qry = PersonDB.Persons.Select(c => c);
what are the differences between using Table<Person>,IEnumerable<Person>,IQueryable<Person>.Any specific need to choose the particular one?
2) For Adding records Add() method not appears in my IDE,(i.e) PersonDB.Persons.Add().
What is the problem here?
1.
IEnumerable<> is an interface that
applies to any collection whose
members can be enumerated or iterated
over.
IQueryable<> is a LINQ interface
that applies to any collection whose
members can be lazily queried.
(queried without materializing the
result set until its members are
accessed)
Table<> is a class that I've
not used before but "represents a
table for a particular type in the
underlying database."
Which one you choose depends on what your needs are, but IEnumerable<> is the most general, so I would use that in my type declarations if it's sufficient.
2.
To insert a person use InsertOnSubmit():
Person person = new Person() { ... };
PersonDB.Persons.InsertOnSubmit(person);
PersonDB.SubmitChanges();
Table(T) is the class that LINQ to SQL uses for query results from a table; it is also used for properties of the data context, so that you can use the data context properties in your queries. So the code in your post is duplicating some code that LINQ is already doing for you. PersonDB.Persons should always be sufficient for querying persons.
For results, you will likely want a collection, so while IEnumerable and IQueryable are fine, you can also consider using a list:
List<Persons> pers = PersonDB.Persons.Where(p => p.name == aName).ToList();
Note that this is an immediate execution, not a lazy (deferred) execution. ToList() forces immediate query execution.
Table<> is well, a table. It can return IQueryable results and can perform inserts/other database specific operations. It is linked to a DataContext.
IQueryable<> is a list that is well, not a list. Basically IQueryable doesn't actually load any data until you actually request it (late execution). As a result you can perform multiple operations before the whole thing is sent to the database. Think of IQueryable<> as an SQL statement in progress, rather then the actual results.
IEnumerable<> is just a standard interface for any list of objects that can be enumerated. When an IQueryable actually executes, you get an IEnumerable set to go through.
Add appears for indvidual instances - for example Person.Add(). For raw tables you should use the Insert* methods.