LINQ query. Two tables - linq

I have 2 tables: user - car:
**User table: ID - Name**
ID:1 Name:Iam
ID:2 Name:Louis
**Car table: ID - Car**
ID:2 Car:BMW
ID:2 Car:Ford
ID:2 Car:Strange
I want to make a query that shows me all users (with or without a car) and their cars. I'm using LINQ to DataSet.
My query is:
var query =
from user in ObjDT_Usuario.AsEnumerable()
join car in ObjDT_Vehiculos.AsEnumerable()
on user.Field<string>("ID") equals car.Field<string>("ID")
orderby user.Field<string>(campo)
select new UserReport
{
Name = user.Field<string>("Name"),
Car = car.Field<string>("Car")
};
This query is correct, but only shows users who have car: on user.Field<string>("ID") equals car.Field<string>("ID")
Someone can help me. Thank you.

This is because you are applying EquiJoin. You need LeftJoin
from user in ObjDT_Usuario.AsEnumerable()
join car in ObjDT_Vehiculos.AsEnumerable()
on user.Field<string>("ID") equals car.Field<string>("ID") into userxs
from u in userxs.DefaultIfEmpty(
orderby u .Field<string>(campo)
select new UserReport
{
Name = user.Field<string>("Name"),
Car = u.Field<string>("Car")
};
Please ignore Typo mistakes. I am not on my laptop.I hope you got an idea

Related

linq query with many-to-many relationship

Let’s assume I have three tables in my database:
Authors(PK Id, AuthorName)
Books(PK Id, BookName)
Authors_Books(FK BookId, FK AuthorId)
I need to write a method which passes in a parameter int[] authorsIds and returns all books (Id, BookName, list of authors of this book) if it was written by any author whose Id contains in int[] authorsIds parameter.
I need LINQ query (query method).
I really need a help. Appreciate your help very much.
var int[] authors = { 1, 2, 3 };
var books = from book in books
where book.Authors.Any(x => authors.Contains(x.AuthorId))
select book;
PS: I assume book.Authors is your reference to Authors_Books table (or maybe has a different name).
this answer is based on the exact structure without considering that A obj has B in its structure
var book = from b in books
where book.Id in ( from ab in AuthersBooks
where selectedAuthers.contains(ab.AutherId)
select ab.bookId ) //now we have books that are authered by one of the selected authers
select new { BookId = b.Id, // now we create an anonymos object to contain any info we need
BookName = b.Name,
BookAuthers = (from a in authers
join ab in AuthersBooks
on a.Id == ab.AuthersId
where ab.bookid == b.Id
select a)
this will propably have syntax errors and after correcting you may get an error about multiple threads which already has an answer here

Need LINQ to EF Query for my given situation

I have to store profiles of farmers. For this I have MST_FarmerProfile as main table which contains personDetails_Id,bankDetails_Id,contactDetails_Id as foreign keys for storing personal details, bank details and contact Details in different tables.
Now the main thing is whenever i update a record, modified details are saved in same table while previous records are saved in personal details history, bank details history and contact Details history tables which again contains personDetails_Id,bankDetails_Id,contactDetails_Id respectively as foreign keys. Basically we need to keep trail of updated records. Following is my database schema:
I have tried using joins but the problem is suppose i update same record two times, each history table will contain 2 rows with same foreign key thus my join gives 2X2X2=8 records, whereas i need only 2.
I did this and it worked:
List<FarmerDetailsReport> fdr =
(from fp in RptdataAccess.MST_FarmerProfile
join pdh in RptdataAccess.PersonalDetailsHistory on fp.personDetails.Id equals pdh.PersonalDetails.Id
join cdh in RptdataAccess.ContactDetailsHistory on fp.contactDetails.Id equals cdh.ContactDetails.Id
join bdh in RptdataAccess.BankDetailsHistory on fp.bankDetails.Id equals bdh.BankDetails.Id
select new FarmerDetailsReport
{
FarmerURNNo = fp.URN_No,
CreatedBy = fp.UserId,
CreatedOn = fp.CreatedOn,
FarmerName = pdh.FarmersName,
FatherOrHusbandName = pdh.FatherHusbandName,
DateofBirth = pdh.DateOfBirth,
Gender = pdh.IsMale.ToLower() == "yes" ? "Male" : "Female",
MaritalStatus = pdh.MaritalStatus,
Religion = pdh.Religion.ToLower() == "other" ? pdh.otherReligion : pdh.Religion,
TypeofBank = bdh.bankType,
BankName = bdh.bankName,
BranchName = bdh.branchName,
BankAccountNo = bdh.bankAccountNo,
Address1 = cdh.Address1,
State = cdh.State,
District = cdh.District,
UpdatedOn = pdh.ChangedOn,
UpdatedBy = pdh.ChangedBy
} ).GroupBy(p => new { p.UpdatedOn }).Select(g => g.FirstOrDefault()).ToList();

Entity Framework returns wrong data after execution of two similar queries

I have two similar queries, the first one:
var activatedSerialNumbers = (from activation in entities.Activations
where !canceledActivationsIds.Contains(activation.Id)
where activation.CustomerId == customerId
join licenseConfiguration in entities.LicenseConfigurations
on activation.Id equals licenseConfiguration.ActivationId
where licenseConfiguration.ProductId == productId
join activatedSerialNumber in entities.ActivatedSerialNumbers
on activation.Id equals activatedSerialNumber.ActivationId
where deactivatedSams.All(dsn => dsn.ToLower() !=
activatedSerialNumber.Name.ToLower())
select new SamWithLicense
{
Name = activatedSerialNumber.Name,
Features = licenseConfiguration.LicenseFeatures
}).ToList();
The second:
var activationsForSam = (from activation in entities.Activations
where !canceledActivationsIds.Contains(activation.Id)
where activation.CustomerId == customerId
let activatedSerialNumbers = activation.ActivatedSerialNumbers
.Select(sn => sn.Name.ToLower())
where activatedSerialNumbers.Contains(loweredSn)
join licenseConfiguration in entities.LicenseConfigurations
on activation.Id equals activatedProduct.ActivationId
select new SamWithLicense
{
Name = selectedSerialNumber,
Features = licenseConfiguration.LicenseFeatures
}).ToList();
In some situations I execute them one after another and in most cases it works fine, but somethimes - not. In the result of second query Counter takes from another row:
Visual Studio - Quick watch
SQL Management Studio
I guess it's a matter of a EF cache or smth, but don't know how to fix it properly.
In your first query you are joining the Activation Id (PK) to LicenseConfigurations ActivationId (FK)
join licenseConfiguration in entities.LicenseConfigurations
on activation.Id equals licenseConfiguration.ActivationId
in your second query, it looks like you are joining on a value defined outside of the query "activatedProduct"
join licenseConfiguration in entities.LicenseConfigurations
on activation.Id equals activatedProduct.ActivationId

Grouping in LINQ to Entity Model

I have following fields in entity model object
MONTH_CHAR char(1)
AVG_BALANCE int
PROD_CAT_ID int
FLG_PERS_COMM chat(1)
ACCOUNT_COUNT int
I want group by MONTH_CHAR column, I 'll write following SQL Query for this
SELECT MONTH_CHAR,
SUM(AVG_BALANCE) AS AVG_BALANCE,
MAX(PROD_CAT_ID) AS PROD_CAT_ID,
MAX(ACCOUNT_COUNT) AS ACCOUNT_COUNT,
FROM contactSummary
WHERE PROD_CAT_ID = 1
GROUP BY MONTH_CHAR
I want this query to be converted to LINQ Query.
Thanks in advance
from contact in context.Contacts
group contact by contact.Month_Char into g
select new
{
MonthChar = g.Key,
AvgBalance = g.Average(x=>x.Avg_Balance)
CatID = g.Max(x=>x.Prod_Cat_ID)
AccountCount = g.Max(x=>x.Account_Count)
}

Subquery nightmares in EF

I'm really, really struggling with what should otherwise be a straightforward query in anything other than LINQ (for example SQL!)
I have two entities:
Product
ProductApprover
The Product entity has a one to many relationship on the ProductApprover entity, e.g:
Product.ProductApprovers gives me all ProductApprover entities relating to the Product.
Getting a Product and associated ProductApprover data is simple enough when querying by my ProductID column on my Product entity as the ProductApprover data associated is bundled into the result automatically, but my problem comes when I want to alter my query by querying data WITHIN my associated ProductApprover entities. I have tried all sorts with use of the 'Where', 'Contains' and 'Any', functions, etc, to perform a subquery, but cannot seem to get the result I want.
The query I want to perform is:
SELECT * FROM Product p
INNER JOIN ProductApprover pa ON p.ProductId = pa.ProductId
WHERE p.ProductId = #id AND pa.Version = #version
Can anybody help me out please? Thank you kindly in advance.
Try this (I guess this is a LINQ interpretation of your SQL query):
int id = 123;
int version = 555;
var results = from p in context.Products
join pa in context.ProductApprovers
on p.ProductId = pa.ProductId
where p.ProductId equals id && pa.Version equals version
select new { Product = p, Approver = pa };
I suspect you want something like this:
var query = from product in db.Products
where product.ProductId == productId
select new {
Product = product,
Approvers = product.Approvers.Where(pa => pa.Version == version)
};
If that doesn't do what you want, could you explain where it falls down?

Resources