LinQ query with multiple tables and extracting data - c#

I'm doing a query to inner join 4 tables and I have to extract data and convert into string and place it in an array for it.
var query = from a in context.as
join b in context.bs on a.prikey equals b.forkey
join c in context.cs on b.prikey equals c.forkey
join d in context.ds on c.prikey equals d.forkey
where b.gender == gender
where c.age == age
select new
{
a.Name,
a.Age,
b.Gender,
};
string[] results = new string[] {}
return results;
Normally, if a single table is involved
a as = plural of table a
as t = query.First()
string[] results = new string[] {t.Name, t.Age, t.Gender}
return results;
I'm missing a step to extract the data.

It depends what exactly you want to do with the data. Your code won't actually compile at the moment as it's trying to create an anonymous type with multiple properties all called "arg" but I'm assuming you've really got a more sensible query.
Ultimately, the fact that you're using multiple tables is irrelevant here - you're only getting a single result element at a time: the fact that each result element contains data from multiple tables is neither here nor there in terms of how you access it.
Now I've just noticed that you say you want to "extract data and convert into string". If possible, you should express that in your query. You may be able to do that at the database, or you may need to force the final part of the execution to execute locally, like this:
// Not executed yet!
var dbQuery = from a in context.a
join b in context.bs on a.prikey equals b.forkey
join c in context.cs on b.prikey equals c.forkey
join d in context.ds on c.prikey equals d.forkey
where ...
select { a.Age, b.Name, c.Salary, d.Location };
// This still won't talk to the database!
var finalQuery = dbQuery.AsEnumerable()
.Select(x => string.format("Age: {0}; Name: {1}; " +
"Salary: {2}; Location: {3}",
x.Age, x.Name, x.Salary,
x.Location));
// This will finally execute the query
string[] results = finalQuery.ToArray();
Now you don't have to do it like this - but it's probably the best approach, at least with the amount of information you've given us. If you can tell us more about how you're trying to combine the data from the multiple tables, we may be able to help you more.
EDIT: Okay, now you've given us a bit more information, I suspect you want:
var query = from a in context.a
join b in context.bs on a.prikey equals b.forkey
join c in context.cs on b.prikey equals c.forkey
join d in context.ds on c.prikey equals d.forkey
where ...
select new string[] { a.arg, b.arg, c.arg, d.arg };
string[] results = query.First();
I haven't tried creating arrays in LINQ to SQL... that may work, or you may need to go via an anonymous type and AsEnumerable as per the earlier part of my answer.
You should also think about what you want to happen if there are no results, or multiple results.
EDIT: Having seen the edited question, you really can treat multiple tables the same way as a single table. You'd use exactly the same code for handling the result, once it's been projected into an anonymous type:
var query = from a in context.as
join b in context.bs on a.prikey equals b.forkey
join c in context.cs on b.prikey equals c.forkey
join d in context.ds on c.prikey equals d.forkey
where ...
select new { a.Name, a.Age, b.Gender };
var result = query.First();
// Call ToString appropriately on each property, of course
string[] array = new string[] { result.Name, result.Age, result.Gender };

var query = from a in context.a
join b in context.bs on a.prikey equals b.forkey
join c in context.cs on b.prikey equals c.forkey
join d in context.ds on c.prikey equals d.forkey
where a.arg == arg
where b.arg == arg
where c.arg == arg
select new
{
allStrings = a.arg +
a.arg +
b.arg +
c.arg +
d.arg
};
string[] results = query.ToArray();

Related

How to translate SQL to LINQ with individual field joins?

I have a SQL statement, that I want to implement in a .NET website project. I don't understand how to join in a particular field, as the fields aren't available when I just select from the table.
My SQL
SELECT *
FROM [vResidence] c
JOIN [vJobs] j on c.UID = j.UID
This is the LINQ I have tried, but I am stuck at the 'ON' part:
results = (from j in vJobs
join cr in vResidence on ??? )
When I try 'j.', the only option I get is 'equals'.
You can follow as this.connect to tables as JOIN use equals keyword
var result = from r in vResidence
join j vJobs on r.UID equals j.UID
select new {[yourcolnum]};
You can try this
var result = (from j in vJobs
join cr in vResidence
on j.UID equals cr.UID
select new {
...
}).ToList();
The Linq expression is the following:
from t1 in Table1
join t2 in Table2
on t1.ID equals t2.ID
The join clause on must be do in order: first the first table, then the second.
The keyword equals must be use.
Apart from the above Linq answers, we can do JOIN using Enumerable.Join extension with Lambda expressions. Try something like,
var result = vJobs.Join(vResidence, jb => new { jb.UID }, res => new { res.UID },
(jb, res) => new { jb, res })
.Select(x => x.jb) //Select the required properties (from both objects) with anonymous object or select left/right object
.ToList();
C# Fiddle with sample data.

C# - Join Syntax with two tables [duplicate]

I'm writing a LINQ to SQL statement, and I'm after the standard syntax for a normal inner join with an ON clause in C#.
How do you represent the following in LINQ to SQL:
select DealerContact.*
from Dealer
inner join DealerContact on Dealer.DealerID = DealerContact.DealerID
It goes something like:
from t1 in db.Table1
join t2 in db.Table2 on t1.field equals t2.field
select new { t1.field2, t2.field3}
It would be nice to have sensible names and fields for your tables for a better example. :)
Update
I think for your query this might be more appropriate:
var dealercontacts = from contact in DealerContact
join dealer in Dealer on contact.DealerId equals dealer.ID
select contact;
Since you are looking for the contacts, not the dealers.
And because I prefer the expression chain syntax, here is how you do it with that:
var dealerContracts = DealerContact.Join(Dealer,
contact => contact.DealerId,
dealer => dealer.DealerId,
(contact, dealer) => contact);
To extend the expression chain syntax answer by Clever Human:
If you wanted to do things (like filter or select) on fields from both tables being joined together -- instead on just one of those two tables -- you could create a new object in the lambda expression of the final parameter to the Join method incorporating both of those tables, for example:
var dealerInfo = DealerContact.Join(Dealer,
dc => dc.DealerId,
d => d.DealerId,
(dc, d) => new { DealerContact = dc, Dealer = d })
.Where(dc_d => dc_d.Dealer.FirstName == "Glenn"
&& dc_d.DealerContact.City == "Chicago")
.Select(dc_d => new {
dc_d.Dealer.DealerID,
dc_d.Dealer.FirstName,
dc_d.Dealer.LastName,
dc_d.DealerContact.City,
dc_d.DealerContact.State });
The interesting part is the lambda expression in line 4 of that example:
(dc, d) => new { DealerContact = dc, Dealer = d }
...where we construct a new anonymous-type object which has as properties the DealerContact and Dealer records, along with all of their fields.
We can then use fields from those records as we filter and select the results, as demonstrated by the remainder of the example, which uses dc_d as a name for the anonymous object we built which has both the DealerContact and Dealer records as its properties.
var results = from c in db.Companies
join cn in db.Countries on c.CountryID equals cn.ID
join ct in db.Cities on c.CityID equals ct.ID
join sect in db.Sectors on c.SectorID equals sect.ID
where (c.CountryID == cn.ID) && (c.CityID == ct.ID) && (c.SectorID == company.SectorID) && (company.SectorID == sect.ID)
select new { country = cn.Name, city = ct.Name, c.ID, c.Name, c.Address1, c.Address2, c.Address3, c.CountryID, c.CityID, c.Region, c.PostCode, c.Telephone, c.Website, c.SectorID, Status = (ContactStatus)c.StatusID, sector = sect.Name };
return results.ToList();
You create a foreign key, and LINQ-to-SQL creates navigation properties for you. Each Dealer will then have a collection of DealerContacts which you can select, filter, and manipulate.
from contact in dealer.DealerContacts select contact
or
context.Dealers.Select(d => d.DealerContacts)
If you're not using navigation properties, you're missing out one of the main benefits on LINQ-to-SQL - the part that maps the object graph.
Use Linq Join operator:
var q = from d in Dealer
join dc in DealerConact on d.DealerID equals dc.DealerID
select dc;
basically LINQ join operator provides no benefit for SQL. I.e. the following query
var r = from dealer in db.Dealers
from contact in db.DealerContact
where dealer.DealerID == contact.DealerID
select dealerContact;
will result in INNER JOIN in SQL
join is useful for IEnumerable<> because it is more efficient:
from contact in db.DealerContact
clause would be re-executed for every dealer
But for IQueryable<> it is not the case. Also join is less flexible.
Actually, often it is better not to join, in linq that is. When there are navigation properties a very succinct way to write your linq statement is:
from dealer in db.Dealers
from contact in dealer.DealerContacts
select new { whatever you need from dealer or contact }
It translates to a where clause:
SELECT <columns>
FROM Dealer, DealerContact
WHERE Dealer.DealerID = DealerContact.DealerID
Inner join two tables in linq C#
var result = from q1 in table1
join q2 in table2
on q1.Customer_Id equals q2.Customer_Id
select new { q1.Name, q1.Mobile, q2.Purchase, q2.Dates }
Use LINQ joins to perform Inner Join.
var employeeInfo = from emp in db.Employees
join dept in db.Departments
on emp.Eid equals dept.Eid
select new
{
emp.Ename,
dept.Dname,
emp.Elocation
};
Try this :
var data =(from t1 in dataContext.Table1 join
t2 in dataContext.Table2 on
t1.field equals t2.field
orderby t1.Id select t1).ToList();
OperationDataContext odDataContext = new OperationDataContext();
var studentInfo = from student in odDataContext.STUDENTs
join course in odDataContext.COURSEs
on student.course_id equals course.course_id
select new { student.student_name, student.student_city, course.course_name, course.course_desc };
Where student and course tables have primary key and foreign key relationship
try instead this,
var dealer = from d in Dealer
join dc in DealerContact on d.DealerID equals dc.DealerID
select d;
var Data= (from dealer in Dealer join dealercontact in DealerContact on dealer.ID equals dealercontact.DealerID
select new{
dealer.Id,
dealercontact.ContactName
}).ToList();
var data=(from t in db.your tableName(t1)
join s in db.yourothertablename(t2) on t1.fieldname equals t2.feldname
(where condtion)).tolist();
var list = (from u in db.Users join c in db.Customers on u.CustomerId equals c.CustomerId where u.Username == username
select new {u.UserId, u.CustomerId, u.ClientId, u.RoleId, u.Username, u.Email, u.Password, u.Salt, u.Hint1, u.Hint2, u.Hint3, u.Locked, u.Active,c.ProfilePic}).First();
Write table names you want, and initialize the select to get the result of fields.
from d1 in DealerContrac join d2 in DealerContrac on d1.dealearid equals d2.dealerid select new {dealercontract.*}
One Best example
Table Names : TBL_Emp and TBL_Dep
var result = from emp in TBL_Emp join dep in TBL_Dep on emp.id=dep.id
select new
{
emp.Name;
emp.Address
dep.Department_Name
}
foreach(char item in result)
{ // to do}

Linq join query with left outer join throwing object reference not found

I have a list and two tables. (This is a very simplified version of the actual schema, but should work for the question)
List_A
FPI
1
2
3
4
Table_B
FPI_______NI
2_________1
4_________2
Table_C
NI_______Name
1_________x
2_________y
My linq query:
(from a in List_A
join b in Table_B on a.FPI equals b.FPI into ab
from b in ab.DefaultIfEmpty()
join c in Table_C on b.FI equals c.FI into bc
from c in bc.DefaultIfEmpty()
select new {
FPI = a.FPI,
Name = c?.Name}).ToList();
this code throws an exception that Object reference not set to an instance of an object..
After a lot of trial and experiment, I have reached to a conclusion that in the second join when i'm doing b.FI equals c.FI, at that time it is failing for the entries for which there is no value in the Table_B.
The expected output of the query should be
ABC
FPI____NI___Name
1_____null__null
2_____1_____x
3_____null__null
4_____2_____y
I'm not sure why this error is coming and what would be the best solution for this problem.
Your query would be perfectly valid if it was a LINQ to Entities query translated to SQL.
However, since the root of the query is List_A which is not a IQueryable, the whole query executes in LINQ to Objects context, where you are supposed to perform null checks on right side variable of the left outer join anywhere, including further join conditions.
So the simple fix would be using
join c in Table_C on b?.FI equals c.FI into bc
However, note that the query is highly inefficient. Since it is resolved to Enumerable methods, the whole Table_B and Table_C will be read in memory and then joined.
A better approach would be to separate the db and in memory queries:
var dbQuery =
from b in Table_B
join c in Table_C on b.FI equals c.FI into bc
from c in bc.DefaultIfEmpty()
select new { b.FPI, c.Name };
var query =
from a in List_A
join bc in dbQuery on a.FPI equals bc.FPI into abc
from bc in abc.DefaultIfEmpty()
select new
{
FPI = a.FPI,
Name = bc?.Name
};
var result = query.ToList();
You can try
var list=(from a in Table_A
join b in Table_B on a.FPI equals b.FPI into ab
from b in ab.ToList()
join c in Table_C on b.NI equals c.NI into bc
from c in bc.DefaultIfEmpty()
select new {
FPI = a.FPI,
Name = c.Name}).ToList();
Update
var list = (from a in Table_A
join b in Table_B on a.FPI equals b.FPI into ab
from b in ab.DefaultIfEmpty()
join c in Table_C on b == null ? 0 : b.NI equals c.NI into bc
from c in bc.DefaultIfEmpty()
select new
{
FBI = a.FPI,
NI = c != null ? c.NI : null,//if NI is nullable
//NI = c != null ? c.NI : 0,//if NI is not nullable
Name = c!=null?c.Name:null
}).ToList();

How to perform a left join with an additional filtering in LINQ to entities?

I have several tables, the main one is called DefectRecord, others are called DefectArea, DefectLevel...etc and the one called DefectAttachment. And this problem is about joining DefectRecord with other tables to get a ViewModel for further use. What the hard part I am facing is about the DefectAttachment table.
DefectRecord has a 1-to-many relation with DefectAttachment. While there may be NO attachment at all for one defect record, there may be multiple attachments.
Logically I tried to perform a left join among DefectRecord & DefectAttachment, but there is one more requiredment:
If there is multiple attachments, select ONLY the oldest one(i.e. the
one with oldest CreatedDate field value)
I am stuck at this requirement, how can I perform this with LINQ-to-Entities? Below is the code of what I have now:
var ret = (from dr in defectRecordQuery
join ft in filterQuery on dr.FilterID equals ft.FilterID
join l in levelQuery on dr.LevelID equals l.LevelID
join a in attachmentQuery on dr.DefectRecordID equals a.DefectRecordID into drd
from g in drd.DefaultIfEmpty()
select new DefectRecordViewModel
{
DefectRecordCode = dr.Code,
DefectAttachmentContent = g == null ? null : g.FileContent,
LookupFilterName = ft.FilterName,
}).ToList();
The *Query variable are the IQueryable object which get the full list of corresponding table.
Group your results by the Code and FilterName and then for the content take that of the item in the group that has the oldest date
var ret = (from dr in defectRecordQuery
join ft in filterQuery on dr.FilterID equals ft.FilterID
join l in levelQuery on dr.LevelID equals l.LevelID
join d in attachmentQuery on dr.DefectRecordID equals d.DefectRecordID into drd
from g in drd.DefaultIfEmpty()
group g by new { dr.Code, ft.FilterName } into gg
select new DefectRecordViewModel
{
DefectRecordCode = gg.Key.Code,
DefectAttachmentContent = gg.OrderByDescending(x => x.CreateDateTime).FirstOrDefault() == null? null: gg.OrderByDescending(x => x.CreateDateTime).FirstOrDefault().FileContent,
LookupFilterName = gg.Key.FilterName,
}).ToList();
If using C# 6.0 or higher then you can do:
DefectAttachmentContent = gg.OrderByDescending(x => x.CreateDateTime)
.FirstOrDefault()?.FileContent,

Correct syntax for multiple left joins in LINQ?

I am trying to figure out the LINQ syntax for multiple left join, but I am getting the error: The name 'c' is not in scope on the left side of 'equals'. Consider swapping the expressions on either side of 'equals'.
I have already tried swapping, and if I do, it makes both 'c' and 'd' have the "not in scope" error.
var result =
from a in db.tableA
join b in db.tableB //first join (inner join)
on a.field1 equals b.field1
join c in db.tableC //second join (left join)
on a.field1 equals c.field1
into left_one
join d in db.tableD //third join (left join)
on c.field2 equals d.field2
// ^ here
into left_two
where a.field1 == theValueImSearchingFor
from c in left_one.DefaultIfEmpty()
from d in left_two.DefaultIfEmpty()
select new CombinedObject()
{
...
}
The reason I am using on c.field2 equals d.field2 in the third join statement is that my tables are structured like this:
tableA: field1
tableB: field1
tableC: field1 field2
tableD: field2
That is, the only way to relate tableD to the rest of the data is to use field2.
Can someone please correct my syntax? Or is there a certain way I have to do it given my setup of tables?
I use this type of syntax:
var results = (from a in db.tableA
from b in db.tableB.Where(s => s.field1 == a.field1)
from c in db.tableC.Where(s => s.field1 == a.field1).DefaultIfEmpty()
from d in db.tableD.Where(s => s.field2 == c.field2).DefaultIfEmpty()
select new CombinedObject() { });
It seems to work well on multiple tables. I think I got my field1s and field2s right to match your example :)
[Edit]
As per the comment, if you want to add in some additional filtering, you just add it in where appropriate into the Where(). Eg:
from c in db.tableC.Where(s => s.field1 == a.field1 && s.field3 == someVariable).DefaultIfEmpty()
Something like that :)

Categories