I have two related tables. Then I use LINQ to query Data.
this is my code
var items = await (from a in queryable
join b in _context.TUserGrant on a.UserNo equals b.UserNo
join c in _context.TProviderInfo on a.ProviderNo equals c.ProviderNo
orderby a.BillNo
select new
{
a.BillNo,
a.NotificeBillNo,
makeName = b.UserName,
a.MakeDate,
a.ProviderNo,
c.ProviderName,
a.CheckTime,
a.CheckAddress,
a.CheckName,
a.StatusTitle,
}).ToListAsync();
My problem is that I need all the columns of the first table, which is all the values of A.
I also need some columns from table B.
I wonder if there is an easy way to get these columns.
Instead of setting them one by one in the SELECT method.
You can try this
var items = await (from a in queryable
join b in _context.TUserGrant on a.UserNo equals b.UserNo
join c in _context.TProviderInfo on a.ProviderNo equals c.ProviderNo
orderby a.BillNo
select new
{
tabA = a,
makeName = b.UserName
}).ToListAsync();
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}
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();
I have one below SQL query, it is more complex having some GroupBy, Conditions, etc. which i skip here in post to make my question easy:
SELECT
SUBSTRING(TSL.ctg_name, 6, 100) AS 'TREKK', *
FROM Filteredctg_timbersettlementline AS TSL
INNER JOIN Filteredctg_timbersettlement AS TS
ON TSL.ctg_timbersettlementid = TS.ctg_timbersettlementid
LEFT JOIN FilteredNew_property AS P
ON TS.ctg_propertyid = P.new_propertyid
WHERE (TS.ctg_timbersettlementid = #TimberSettlementID) AND
(TSL.ctg_reportgroup = 'TREKK')
I tried below Linq:
var Trekks = (from ts in XrmContext.ctg_timbersettlementSet
join tsl in XrmContext.ctg_timbersettlementlineSet
on ts.Id equals tsl.ctg_timbersettlementid.Id
join p in XrmContext.New_propertySet
on ts.ctg_propertyid.Id equals p.New_propertyId
into temp
from p in temp.DefaultIfEmpty()
where ts.ctg_timbersettlementId == TimberSettlementGuid
where tsl.ctg_reportgroup == "TREKK"
select new
{
tsl.ctg_name,
ts.ctg_BasisAllocatedForestryFund,
}).ToList();
It throwing me an error:
The method 'GroupJoin' cannot follow the method 'Join' or is not supported. Try writing the query in terms of supported methods or call the 'AsEnumerable' or 'ToList' method before calling unsupported methods.
How can i achive LEFT JOIN?
To achieve a left join, you need to use an intermediary DefaultIfEmpty() :
var query = from c in db.Customers
join o in db.Orders
on c.CustomerID equals o.CustomerID into sr
from x in sr.DefaultIfEmpty()
select new {
CustomerID= c.CustomerID, ContactName=c.ContactName,
OrderID = x.OrderID == null ? -1 : x.OrderID};
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();