detail rows not included query with entity framework 7 - c#

I have this query in entity framework 7 that queries a list of invoices, including details rows and customers.
First the data are estracted and after a model class is filled extracting some fields from the invoice, the name of the customer, and the sum of the values from the rows.
var clienti = db.Fatture
.OrderByDescending(cli => cli.DataFattura).ThenByDescending(cli => cli.NumFattura)
.Include(cli => cli.Cliente).Include(cli => cli.Righe)
.Take(recNum)
.ToList();
return clienti.Select( cli => new FatturaVm {
FatturaNo = cli.FatturaNo,
Cliente = cli.Cliente.Descrizione,
Data = cli.DataFattura.Value.ToString("dd/MM/yyyy"),
Importo = cli.Righe.Sum( rg => rg.Importo.Value),
NumeroDocumento = cli.NumFattura.Value + "/" + cli.Anno.Value
}).ToList();
I found a strange thing: if I add the OrderByDescending the invoices are returned with an empty list of the rows, but if I remove the ordering the rows are returned with the details.
Am I missing something?

Related

C# LINQ JOIN LAMBDA Add list of columns from second joined table

I have a linq query that joins 3 tables, which there is a left outer join on the 2nd table. I am stuck on how to add a few columns from the 2nd table to my output object.
What I have so far is the following
I am stuck for each user record, there is a List that could be 0 to many records.
How do I add those list of selected columns from the office table based on office.userId that matches user.userId?
for example, I need to select from office table, officeSuiteNumber, officeName, officeStartDate, officeEndDate?
I prefer to add it this query instead of looping again and adding the list to each record and adding more processing time.
Thanks for any help.
var result = this.dbContext.User
.GroupJoin(this.dbContext.Office,
user => user.userId,
office => office.userId,
(user, office) => new { user, office }
)
.SelectMany(
user_office_left => user_office_left.office.DefaultIfEmpty(),
(user_office_left, office) => new { user_office_left, office }
)
.Join(this.dbContext.Dept,
user_office => user_office.user_office_left.user.DivisionId,
dept=> division.DivisionId,
(emp_office, dept) => new { emp_office, dept}
)
.Select(joined => new MyViewModel
{
userId = joined.user_office.user_offce_left.user.userId,
LastNm = joined.user_office.user_offce_left.user.LastNm,
FirstNm = joined.user_office.user_offce_left.user.FirstNm,
Title = joined.user_office.user_offce_left.user.Title,
DivisionNm = joined.division.ShortDivisionNm,
offices = ???? // how to add the list of office that could be 0 to many records
}).ToList();

EF6 IN clause on specific properties

Good morning,
I'm having trouble with a EF query. This is what i am trying to do.
First i am pulling a list of ID's like so (List of IDs are found in the included x.MappingAccts entity):
Entities.DB1.Mapping mapping = null;
using (var db = new Entities.DB1.DB1Conn())
{
mapping = db.Mappings.Where(x => x.Code == code).Include(x => x.MappingAccts).FirstOrDefault();
}
Later, i'm trying to do a query on a different DB against the list of Id's i pulled above (essentially a IN clause):
using (var db = new Entities.DB2.DB2Conn())
{
var accounts = db.Accounts.Where(mapping.MappingAccts.Any(y => y.Id == ?????????)).ToList();
}
As you can see i only got part way with this.
Basically what i need to do is query the Accounts table against it's ID column and pull all records that match mapping.MappingAccts.Id column.
Most of the examples i am finding explain nicely how to do this against a single dimension array but i'm looking to compare specific columns.
Any assist would be awesome.
Nugs
An IN clause is generated using a IEnumerable.Contains.
From the first DB1 context, materialize the list of Id's
var idList = mapping.MappingAccts.Select(m => m.Id).ToList();
Then in the second context query against the materialized list of id's
var accounts = db.Accounts
.Where(a => idList.Contains(a.Id))
.ToList();
The only problem you may have is with the amount of id's you are getting in the first list. You may hit a limit with the SQL query.
This will give the list of Accounts which have the Ids contained by MappingAccts
using (var db = new Entities.DB2.DB2Conn())
{
var accounts = db.Accounts.Where(s => mapping.MappingAccts.Any(y => y.Id == s.Id)).ToList();
}

Get first N Rows from Database using Entity Framework

My process to get first N rows
Get All Data from Database using Entity Framework
var list = new MyDbContext().Set<EntityName>();
Get First N rows using C#
var firstNRows = list.Take(N); // N = int
Suppose,
If N = 2 then I want the first 2 rows of the table but entity give me all rows of the table. Is there any way that entity give me only first N rows from the table not all data from the table?
Actually var list = new MyDbContext().Set<EntityName>(); gets no data at all, it returns a IQueryable<EntityName> which is just a representation of a query of all rows.
When you do var firstNRows = list.Take(N); that also gets no data, that also is a IQueryable<EntityName> which is a representation of a query of the first N rows in the database.
You don't actually get data from the database until you do something like a .ToList()
var firstNRowsList = firstNRows.ToList(); //The database is queried here for the first time.
var awards = await _context.Awards.AsNoTracking()
.OrderBy(x => x.Id)
.Take(15)
.ToListAsync();

Entity framework get (unique) number of times ID is present in event

We have shopping list DataTable that holds ingredients. One ingredient can be added to shopping list more then once.
What I would like to select is: on how many shopping lists is one ingredient present. Even if ingredient is present multiple times on one shopping list query should return 1.
In short: I need COUNT of ShoppingListIngredients that contains ingredientId (no matter, once or multiple times)
I have tried like this:
var usersShoppingListIngredients = context.ShoppingListIngredients
.Where(sli => sli.ShoppingList.userId == userId)
.GroupBy(sli => sli.ingredientId)
.Select(sli => new
{
itemId = sli.Key,
item = sli.FirstOrDefault().CodingKeys.Ingredients.FirstOrDefault(i => i.languageId == languageId).coding,
itemsCount = sli.Count(),
percent = [Tell_Me_How] * 100 / totalPurchases
}).OrderByDescending(r => r.itemsCount);
But it returns me false value - it returns number of all occurrences when multiple values are inserted.
I am using Entity Framework 4.0.
Any hint would be greatly appreciated ;)
Try this itemsCount = sli.DistinctBy(s => s.ShoppingListId).Count()

wpf and ef select part of a table with include

I have a table with many fields and I want to get only a few individual fields, I work with EF and I add another table to the query as follows
var Test= ve.Folders.Include("Hosting")
.Where(a => a.Collateral!= true)
.AsEnumerable()
.Select(p => new
{
id = p.Folder_Id,
name = p.Full_Name,
add = p.Address,
date1 = p.Collateral_Date,
sName = p.Hosting._Name
})
.ToArray();
But with the field (sName= p.Hosting._Name) that is associated with the second table without any value query not working
Many attempts have been tried but without result (interesting when I ask without Select everything works well)
Thanks in advance for any help
One thing to note is that, in this case, there's little benefit to the Select after the call to AsEnumerable, since all the data in the table is still queried from the database (not just the fields you specifiy).
If you want to avoid that, and only query those five fields, you can remove the AsEnumerable call. That means the Select will execute as part of the SQL query. This also means the Include is unnecessary, since the Select will query all of the data you want.
var Test= ve.Folders
.Where(a => a.Collateral!= true)
.Select(p => new
{
id = p.Folder_Id,
name = p.Full_Name,
add = p.Address,
date1 = p.Collateral_Date,
sName = p.Hosting._Name
})
.ToArray();

Categories

Resources