Generic OrderBy - c#

I'm new on development and want to make a small change by adding orderby to the existing code. Can someone enlighten me on how to orderby to this piece of code?
public List<Employee> GetAllEmployees()
{
ebll employeeBll = new EmployeeBLL();
return ebll.GetAllEmployees();
}

I agree with the answer that T.S. gave, however I would modify to return an IQueryable instead of returning the a .ToList() if you want to leave the option to further filter the list in the calling method. For example GetAllEmployees().Where(e=>e.Name="Brad") otherwise you are enumerating the list early and not taking advantage of using the underlying data source to do the heavy lifting of filtering therefore returning more data than is needed.

Set reference to Linq before doing this. I used employee LastName for order by
public List<Employee> GetAllEmployees()
{
ebll employeeBll = new EmployeeBLL();
return ebll.GetAllEmployees().OrderBy(e => e.LastName).ToList();
}

Related

Results IOrderedEnumerable is null outside context

I'm learning entity framework and hitting a wall. Here is my code:
public IOrderedEnumerable<ArchiveProcess> getHistory()
{
using (ArchiveVMADDatabase.ArchiveDatabaseModel dataContext = new ArchiveDatabaseModel())
{
var query = (from history in dataContext.ArchiveProcess.AsNoTracking()
orderby history.ArchiveBegin descending
select history).Take(10).ToList();
return query as IOrderedEnumerable<ArchiveProcess>;
}
}
When I step through this code, query is a List<ArchiveProcess> containing my ten desired results. However, as soon as I exit the method and the context is disposed of, query becomes null. How can I avoid this? I tried doing this instead:
select new ArchiveProcess
{
ArchiveBegin = history.ArchiveBegin,
ArchiveEnd = history.ArchiveEnd,
DeploysHistoryCount = history.DeploysHistoryCount,
MachinesHistory = history.MachinesHistory,
ScriptHistory = history.ScriptHistory
}
But then I received a NotSupportedException. Why does entity framework delete my precious entities as soon as the context is disposed of and how do I tell it to stop?
I think there are several ways to avoid this but in general you should know precisely how long you want your context to live. In general it's better to have the using statement wrapped through the entire method.
In order to avoid the garbage collection you can do something like this: set the object in memory and then add value to that object.
List<ArchiveProcess> query;
using (ArchiveVMADDatabase.ArchiveDatabaseModel dataContext = new ArchiveDatabaseModel())
{
query = (from history in dataContext.ArchiveProcess.AsNoTracking()
orderby history.ArchiveBegin descending
select history).Take(10).ToList();
return query; /// you do not really need to all enumerable as IOrderedEnumerable<ArchiveProcess>;
}
query as IOrderedEnumerable<ArchiveProcess>;
query is a List<ArchiveProcess>, as returns null when you try use it to cast something to an interface it doesn't implement. List<ArchiveProcess> is not an IOrderedEnumerable<ArchiveProcess> so query as IOrderedEnumerable<ArchiveProcess> is null.
The only thing that IOrderedEnumerable<T> does that IEnumerable<T> doesn't do, is implement CreateOrderedEnumerable<TKey>, which can be called directly or through ThenBy and ThenByDescending, so you can add a secondary sort on the enumerable that only affects items considered equivalent by the earlier sort.
If you don't use CreateOrderedEnumerable() either directly or through ThenBy() or ThenByDescending() then change to not attempt to use it:
public IEnumerable<ArchiveProcess> getHistory()
{
using (ArchiveVMADDatabase.ArchiveDatabaseModel dataContext = new ArchiveDatabaseModel())
{
return (from history in dataContext.ArchiveProcess.AsNoTracking()
orderby history.ArchiveBegin descending
select history).Take(10).ToList();
}
}
Otherwise reapply the ordering, so that ThenBy etc. can be used with it:
public IOrderedEnumerable<ArchiveProcess> getHistory()
{
using (ArchiveVMADDatabase.ArchiveDatabaseModel dataContext = new ArchiveDatabaseModel())
{
return (from history in dataContext.ArchiveProcess.AsNoTracking()
orderby history.ArchiveBegin descending
select history).Take(10).ToList().OrderBy(h => h.ArchiveBegin);
}
}
However this adds a bit more overhead, so don't do it if you don't need it.
Remember, IOrderedEnumerable<T> is not just an ordered enumerable (all enumerables are in some order, however arbitrary), it's an ordered enumerable that has knowledge about the way it which it is ordered so as to provide for secondary sorting. If you don't need that then you don't need IOrderedEnumerable<T>.
using (ArchiveVMADDatabase.ArchiveDatabaseModel dataContext = new ArchiveDatabaseModel())
{
var query = dataContext.ArchiveProcess.AsNoTracking().Take(10).OrderBy(o=> o.ArchiveBegin);
return query;
}

How to transfer the data from Data Base to VIEW via PRESENTER?

I'm trying to create app that implements MVP pattern using WinForms.
Wherein I'm also using EF+CodeFirst+Linq.
On the VIEW there is DataGridView control, that need filling a data. The VIEW call a method SELECT() of PRESENTER class, which in turn call a method SELECT() of MODEL class.
How to transfer the data from Data Base to VIEW via PRESENTER?
I'm trying to use return but it not work because i'm using the USING block.
internal void Select()
{
using (GoodsContext context = new GoodsContext())
{
var items = from Items in context.Goods
select Items;
}
}
Quite interesting question. Of course one can materialize the query and return it as IEnumerable, but I was wondering what is the way to return it as IQueryable, to allow further filtering/sorting etc. The only way I see is to not dispose the DbContext (apparently the returned queryable keeps reference to it), but is it safe? Then I've googled and found this Do I always have to call Dispose() on my DbContext objects? Nope. The explanation inside sounds reasonable to me, and we already have a disposable object (Task) that we are not supposed to Dispose.
Shortly, you can remove the using statement and return the IQueryable.
Change return type of Select method to List<Good>
Then "materialize" result to the List of data, and you will not depend on the DataContext
internal List<Good> Select()
{
using (GoodsContext context = new GoodsContext())
{
return context.Goods.Select(items => items).ToList();
}
}
You should change type of method Select from void to IEnumerable<Good> to be able to return something. Also use .ToList to materialize result to a List:
internal IEnumerable<Good> Select()
{
using (GoodsContext context = new GoodsContext())
{
var items = (from Items in context.Goods
select Items).ToList();
return items;
}
}

Custom Method in LINQ Query

I sum myself to the hapless lot that fumbles with custom methods in LINQ to EF queries. I've skimmed the web trying to detect a pattern to what makes a custom method LINQ-friendly, and while every source says that the method must be translatable into a T-SQL query, the applications seem very diverse. So, I'll post my code here and hopefully a generous SO denizen can tell me what I'm doing wrong and why.
The Code
public IEnumerable<WordIndexModel> GetWordIndex(int transid)
{
return (from trindex in context.transIndexes
let trueWord = IsWord(trindex)
join trans in context.Transcripts on trindex.transLineUID equals trans.UID
group new { trindex, trans } by new { TrueWord = trueWord, trindex.transID } into grouped
orderby grouped.Key.word
where grouped.Key.transID == transid
select new WordIndexModel
{
Word = TrueWord,
Instances = grouped.Select(test => test.trans).Distinct()
});
}
public string IsWord(transIndex trindex)
{
Match m = Regex.Match(trindex.word, #"^[a-z]+(\w*[-]*)*",
RegexOptions.IgnoreCase);
return m.Value;
}
With the above code I access a table, transIndex that is essentially a word index of culled from various user documents. The problem is that not all entries are actually words. Nubers, and even underscore lines, such as, ___________,, are saved as well.
The Problem
I'd like to keep only the words that my custom method IsWord returns (at the present time I have not actually developed the parsing mechanism). But as the IsWord function shows it will return a string.
So, using let I introduce my custom method into the query and use it as a grouping parameter, the is selectable into my object. Upon execution I get the omninous:
LINQ to Entities does not recognize the method
'System.String IsWord(transIndex)' method, and this
method cannot be translated into a store expression."
I also need to make sure that only records that match the IsWord condition are returned.
Any ideas?
It is saying it does not understand your IsWord method in terms of how to translate it to SQL.
Frankly it does not do much anyway, why not replace it with
return (from trindex in context.transIndexes
let trueWord = trindex.word
join trans in context.Transcripts on trindex.transLineUID equals trans.UID
group new { trindex, trans } by new { TrueWord = trueWord, trindex.transID } into grouped
orderby grouped.Key.word
where grouped.Key.transID == transid
select new WordIndexModel
{
Word = TrueWord,
Instances = grouped.Select(test => test.trans).Distinct()
});
What methods can EF translate into SQL, i can't give you a list, but it can never translate a straight forward method you have written. But their are some built in ones that it understands, like MyArray.Contains(x) for example, it can turn this into something like
...
WHERE Field IN (ArrItem1,ArrItem2,ArrItem3)
If you want to write a linq compatible method then you need to create an expresion tree that EF can understand and turn into SQL.
This is where things star to bend my mind a little but this article may help http://blogs.msdn.com/b/csharpfaq/archive/2009/09/14/generating-dynamic-methods-with-expression-trees-in-visual-studio-2010.aspx.
If the percentage of bad records in return is not large, you could consider enumerate the result set first, and then apply the processing / filtering?
var query = (from trindex in context.transIndexes
...
select new WordIndexModel
{
Word,
Instances = grouped.Select(test => test.trans).Distinct()
});
var result = query.ToList().Where(word => IsTrueWord(word));
return result;
If the number of records is too high to enumerate, consider doing the check in a view or stored procedure. That will help with speed and keep the code clean.
But of course, using stored procedures has disadvatages of reusability and maintainbility (because of no refactoring tools).
Also, check out another answer which seems to be similar to this one: https://stackoverflow.com/a/10485624/3481183

SQL "not in" syntax for Entity Framework 4.1

I have a simple issue with Entity Framework syntax for the "not in" SQL equivalent. Essentially, I want to convert the following SQL syntax into Entity Framework syntax:
select ID
from dbo.List
where ID not in (list of IDs)
Here is a method that I use for looking up a single record:
public static List GetLists(int id)
{
using (dbInstance db = new dbInstance())
{
return db.Lists.Where(m => m.ID == id);
}
}
Here is a pseudo-method that I want to use for this:
public static List<List> GetLists(List<int> listIDs)
{
using (dbInstance db = new dbInstance())
{
return db.Lists.Where(**** What Goes Here ****).ToList();
}
}
Can anyone give me pointers as to what goes in the Where clause area? I read some forums about this and saw mention of using .Contains() or .Any(), but none of the examples were a close enough fit.
Give this a go...
public static List<List> GetLists(List<int> listIDs)
{
using (dbInstance db = new dbInstance())
{
// Use this one to return List where IS NOT IN the provided listIDs
return db.Lists.Where(x => !listIDs.Contains(x.ID)).ToList();
// Or use this one to return List where IS IN the provided listIDs
return db.Lists.Where(x => listIDs.Contains(x.ID)).ToList();
}
}
These will turn into approximately the following database queries:
SELECT [Extent1].*
FROM [dbo].[List] AS [Extent1]
WHERE NOT ([Extent1].[ID] IN (<your,list,of,ids>))
or
SELECT [Extent1].*
FROM [dbo].[List] AS [Extent1]
WHERE [Extent1].[ID] IN (<your,list,of,ids>)
respectively.
This one requires you to think backwards a little bit. Instead of asking if the value is not in some list of ids, you have to ask of some list of id's does not contain the value. Like this
int[] list = new int[] {1,2,3}
Result = (from x in dbo.List where list.Contains(x.id) == false select x);
Try this for starters ...
m => !listIDs.Contains(m.ID)
This might be a way to do what you want:
// From the method you provided, with changes...
public static List GetLists(int[] ids) // Could be List<int> or other =)
{
using (dbInstance db = new dbInstance())
{
return db.Lists.Where(m => !ids.Contains(m.ID));
}
}
However I've found that doing so might raise error on some scenarios, specially when the list is too big and connection is somewhat slow.
Remember to check everything else BEFORE so this filter might have less values to check.
Also remember that Linq does not populate the variable when you build your filter/query (at least not by default). If you're going to iterate for each record, remember to call a ToList() or ToArray() method before, unless each record has 500MB or more...

LINQ: Checking if a field (db) contains items in an ILIST?

I am trying to create an extension method that i can forward a IList of statuses and check weather they exist, I thought the best way to do this was an ILIST - but maybe i wrong? Is this the best way to pass multple items to a method - A List? Its a generic LIST so hence no conversion etc from Object.
Basically I have this as a signature.
public static IQueryable<Building> WithStatus(this IQueryable<Building> qry,
IList<BuildingStatuses> buildingStatus)
{
//PSUEDO CODE
//return from v in qry
// where v.Status is IN MY LIST called buildingStatus
// select v;
}
and to call it i use (example below is in my TDD), it works great the values arrive in my method above.
target.GetBuildings().WithStatus(new List<BuildingFilters.BuildingStatuses>()
{ BuildingFilters.BuildingStatuses.Available,
BuildingFilters.BuildingStatuses.Decommissioned });
so basically i have my list (IList) it arrives in the extension method with 2 values which is great but need to say in LINQ i need to say
return from v in qry
where v.Status is IN MY LIST called buildingStatus
select v;
Really appreciate any help,
with regards to my extension method, it works as i have done similar 1 but only passing type BuildingStatus hence only 1...
would this work for you:
return from v in qry
where buildingStatus.Contains(v.Status)
select v;
The suggested approaches I believe are correct... you should also keep in mind the IEnumerable<T>.Where method.
http://msdn.microsoft.com/en-us/library/bb910023.aspx
You can use the IEnumerable<T>.Contains extension method and allow your method to be more versatile:
public static IQueryable<Building> WithStatus(this IQueryable<Building> qry,
IEnumerable<BuildingStatuses> buildingStatus)
{
return from v in qry
where buildingStatus.Contains(v.Status)
select v;
}

Categories