Tags down


How to shorten the LINQ query to calculate the sum for parent table from child tables

By : psriram
Date : September 13 2020, 09:00 AM
This might help you Currently I have this LINQ query which calculate the totalcount of a parent table (CafeTables) from child tables (CafeTableDetails). These code works. But somehow, I believe these code can the shorten. , I think you can try to use linq JOIN and GroupBy to make it.
code :
var result = db.CafeTables.Where(c => c.TableNo == userName)
                         .Select(g => new { CafeTableId = g.Key, cnt = g.Count() }), 
st => st.Id,
cd => cd.CafeTableId,
(st,cd) => new  
    //..... your expect property

Share : facebook icon twitter icon

Load parent and child table in one query linq to entitiy

By : Jennifer Anderson
Date : March 29 2020, 07:55 AM
it fixes the issue I have a following tables/classes structure in Linq to entities.
code :
(from b in books
select new { BookId = b.BookId,
             Title = b.Title,
             Tags = bookTag.Where(bt => bt.BookId == b.BookId).Select(bt => tags.Single(t => t.TagId == bt.TagId).TagTitle)
           }).ToList().Select( t => new 
           { BookId = b.BookId,
             Title = b.Title,
             Tags = string.Join(", ", t.Tags.ToArray())

LINQ to SQL join two tables to select parent table twice based on two different columns from child table

By : user2239435
Date : March 29 2020, 07:55 AM
Hope this helps I'd like to get suggestion in both C# and VB.NET , This should do it in C#:
code :
var query = from log in db.CafeLogs
            join emp in db.Employees on log.EmployeeId equals emp.EmployeeId
            join cas in db.Employees on log.CashierId  equals cas.EmployeeId
            select new
                Employee  = emp.FirstName + " " + emp.LastName,
                ChargedBy = cas.FirstName + " " + cas.LastName,
Dim query = From log In db.CafeLogs                                          _
            Join emp In db.Employees On log.EmployeeId Equals emp.EmployeeId _
            Join cas In db.Employees On log.CashierId  Equals cas.EmployeeId _
            Select                                                           _
                log.LogId,                                                   _
                Employee  = emp.FirstName & " " & emp.LastName,              _
                ChargedBy = cas.FirstName & " " & cas.LastName,              _

LINQ Query for outerjoining Parent and child (nested) tables

By : Θοδωρής Παλτόγλου
Date : March 29 2020, 07:55 AM
I hope this helps you . I have three levels of tables "Directors", "Managers" and "Leaders" with one to many relationship between them. ,
It feels like a small tweak
code :
var query =
db.Directors.GroupJoin(db.Managers, director => director.DirectorId, manager => manager.DirectorId, (director, managerGroup) => new
    Id = director.DirectorID,
    Name = director.DirectorName,
    Managers = managerGroup.GroupJoin(db.Leaders, manager => manager.ManagerId, leader => leader.ManagerID, (manager, leaderGroup) => new
        Id = manager.ManagerID,
        Name = manager.ManagerName,
        Leaders = leaderGroup.Select(leader => new
            Id = leader.LeaderID,
            Name = leader.LeaderName
.SelectMany(director =>  
    new[] { new
        DirID = director.Id, DirectorName = director.Name,
        MgrID = (int?)null, ManagerName = (string)null,
        LdrID = (int?)null, LeaderName = (string)null
    } }
    .Concat(director.Managers.SelectMany(manager => 
        new[] { new
            DirID = director.Id, DirectorName = director.Name,
            MgrID = (int?)manager.Id, ManagerName = manager.Name,
            LdrID = (int?)null, LeaderName = (string)null
        } }
        .Concat(manager.Leaders.Select(leader => new
            DirID = director.Id, DirectorName = director.Name,
            MgrID = (int?)manager.Id, ManagerName = manager.Name,
            LdrID = (int?)leader.Id, LeaderName = leader.Name

Linq get parent and child in one table and calculate their values in another table

By : Rebb Dellah
Date : March 29 2020, 07:55 AM
it helps some times I have 2 tables: , Assuming the table names acc.
code :
var parentRecords = records.Select(x => 
        new Record { RecordID = parents.FirstOrDefault(y => y.ChildID == x.RecordID || y.ParentID == x.RecordID).ParentID, Quantity = x.Quantity});

    var result = parentRecords.GroupBy(z => z.RecordID,
        (key, value) => new { RecordID= key, TotalQuantity= value.Sum(a => a.Quantity) });

Filter parent/child table (one to many association) in linq query based on entities in child table?

By : user3896224
Date : March 29 2020, 07:55 AM
Does that help I have a table (Projects) which is linked to projectVersions on projectID , If I understand correctly, the issue is in
Related Posts Related Posts :
  • Visual Studio 2019: how to disable specific CodeAnalysis messages in .editorconfig?
  • Pass ID to controller on prev or next
  • What are the difference using app.run and app.useendpoints in asp.net-core?
  • Why string Method(Object object) may not match Func<Object, string> delegate type?
  • Check inside loop if *txt file has been created
  • C# retry logic While loop
  • Convert object {object[]} to string[]
  • Difference between initialize a string to "" or to "".ToString() - Which one should I use?
  • How to make the console wait but then continue without pressing a Key?
  • extract text in rich text format from range
  • how to handle 1000 concurrent user requests per second in asp.net web api
  • In C# How to get Windows Credentials from credential manager
  • Override default value of null conditional operator
  • How to fix override ToString method
  • System.IO.FileNotFoundException when creating EF migrations on .net core
  • Login limit attempts in C#
  • Loop into ListView elements
  • Changing Blazor folder gives me "Cannot find the fallback endpoint"
  • creating class from JSON with different types of a node
  • How to define models for Database tables in C# without using Linq To DB?
  • Understanding Identityserver4 with Identity (cookies/tokens, server architecture)
  • How to Deserialize a JSON into a list using SIMPLE JSON?
  • another option instead using AsEnumerable() in linq EF, when using custom method in linq
  • Parameterized query that returns TEXT column(s) always returns zero for INT columns
  • Why format is not working while appending zeros?
  • SqlConnection string
  • Entity Framework Core Update Database - Code First Approach Without Migration
  • Unity Update Method
  • Custom Middleware is causing Blazor Server-side page to stop working
  • Declaring hex number: The name 'B9780' does not exist in the current context
  • Invalid cast from 'System.Int32' to Enum using reflections
  • Why does my webrequest line need updating? (error (426) Upgrade Required )
  • How to generate Key and Key IV aes in C#
  • How can I display view inside content control in wpf
  • How can I wait for form2 to finish?
  • Is Application.DoEvents() a form of Multitasking?
  • In C#, how can I see if the first character in an account is a specific value?
  • C# Determine if a char at index is between two characters in a string
  • C# - Winform Timer - Disposing and emptying the timer
  • if else condition in Regex c# and return constant value
  • Ternary operator for 3 conditions
  • Fineuploader with Azure, Empty image problem
  • How do I unit test the event raised by class under test?
  • How to set up .net core service that uses a generic repository
  • ASP.NET Core 3.0 Endpoint Routing doesn't work for default route
  • use gmail API token on localhost and hosting at the same time
  • Try-catch FormatException
  • why do sql procedure retuns 0 rows when called from applciation?
  • .Net core 3: The namespace internal does not exist in Microsoft.Extensions.Logging.Internal
  • how to interpolate a variable into string method
  • I want to instantiate an object at the location of another object which is destroyed
  • How to display full path of ALL currently running process in C#?
  • How do I return a LinkedList collection from a lambda?
  • How would I represent the following JSON layout as a C# object?
  • Need a fix for this implicit cast error in my find median method
  • How to write code for Server side pagination in ASP.NET Core
  • Bot Emulator Framework Unable to resolve service
  • How to use WebSocket in one server and access it in another PC in the same LAN?
  • Handling an ViewModel command on Item Select
  • Descending Order By Month SQL when date type is varchar using C# csharp
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk