Pulling out different columns from different tables using LINQ - c#

I have two tables:
Entity
ID (PK), int
Name
Descrip
Users
ID (PK)
EntityID, int (this is not connected to Entity table)
Now I am using LINQ to pull the records which has a Entity.ID = something. Which will show me couple of records in my GridView.
Here is my LINQ statement:
protected void Page_Load(object sender, EventArgs e)
{
string getEntity = Request.QueryString["EntityID"];
int getIntEntity = Int32.Parse(getEntity);
OISEntityTestingDataContext db = new OISEntityTestingDataContext();
//OISLinqtoSQLDataContext db = new OISLinqtoSQLDataContext();
var tr =
from r in db.Users
join s in db.Entities on r.UserID equals s.ID
where s.ID == getIntEntity
select new
{
//To Show Items in GridView!
};
GridView1.DataSource = tr;
GridView1.DataBind();
}
Now here I am getting an error mesg on 'join':
The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'Join'.
What does that mean? Can someone please help me on this. Thank you!

Basically the error you receive tells you that the compiler does not know a way to compare the two values because one is different from the another. Are you sure that you are not comparing a string to an int? If this is your case you can obviously parse the string as shown below:
var tr =
from r in db.Users
join s in db.Entities on int.Parse(r.UserID) equals s.ID
where s.ID == getIntEntity
select new
{
//To Show Items in GridView!
};

I'd wager that the type of one of your join conditions doesn't match the type of the other.
The type of one of the expressions in the join clause is incorrect.
Make sure they match in your entity mappings.
In your post you list your tables as having a column "ID" but in the join one is ID and the other is UserID. Are you sure your joining on the correct column?

Related

Select all columns from one table and 1 column from another

I have the following query in linq:
(from creditCard in DbSet
join rank in base.dataContext.ProductVerticalRanks on creditCard.ProductVerticalReferenceId equals rank.ProductVerticalReferenceId
where rank.ClientId == clientId
orderby rank.PreferredOrder
select creditCard)
.Include(creditCard => creditCard.ProductVerticalCompany)
.Include(creditCard => creditCard.Labels);
But now I have a new requirement, I need to add a column 'rank.PreferredOrder' from table 'rank' into the result, is there an easy way of doing this without making a massive 'select' statement, because there are around 20-30 fields in creditCard alone.
I dont have your model in front of me, so can't confirm this or not, but you can use an anonymous object like this:
from creditCard in DbSet
join rank in base.dataContext.ProductVerticalRanks on
creditCard.ProductVerticalReferenceId equals rank.ProductVerticalReferenceId into g
where rank.ClientId == clientId
orderby rank.PreferredOrder
select new {Card = creditCard, Ranks = g}

how to get the max value of id from second table using join in entity framework in asp.net c#

I have two tables, from 1st table i want to get all records and from 2nd table i want the max id value of that record. I am using entity framework in asp.net c#.
i tried the below code but it takes only single record from first table i.e tblblogs. and leave all the records, how to get all those records by using this query? plz help me out I'll be very grateful to you. Thanks !
var query= (from c in db.tblBlogs join a in db.tblBlogMedias on c.id
equals a.BlogId where c.id==db.tblBlogMedias.Max(p=>p.id)
select new
{}
If I understood, you want to get an object with specific fields of Blogs and a list of tblBlogMedias.
You could try this code:
var query2 = (from c in db.tblBlogs
orderby c.Id descending
group c.tblBlogMedias by new { c.Id, c.Name } into gb //It will show Id and name of tblBlogs, you can use more fields if you want
select new {
Id = gb.Key.Id,
Name = gb.Key.Name, //I don't know if you have this field, but you should change it
SecondTable = gb.ToList()
})
.OrderByDescending(o => o.Id) //this orderby with FirstOrDefault() replace where c.id==db.tblBlogMedias.Max(p=>p.id)
.FirstOrDefault();

Linq to Sql - Manual association with manual parameter

I have the following tables in my database:
SageAccount
ID (bigint)
LegacyID (nvarchar)
Customer (bit)
Consignments
ID (bigint)
Customer (nvarchar)
What I want to do is have a navigation property/association in my Linq to Sql dbml from Consignment to SageAccount. The difficulty with this is that not only do we need to match SageAccount.LegacyID => Consignments.Customer but we also need to only join to sage accounts where SageAccount.Customer is TRUE. So on the Consignments end, it isn't joining onto a field but instead a static value.
Is this possible in Linq to Sql? Note this database doesn't (and unfortunately can't) have any foreign keys setup in the database.
Yes it is possible. linq have join method. You can use it ike this in your situation:
var res = from sageAccount in _context.SageAccount
join consignments in _context.Consignments
on
new
{
LegacyID = sageAccount.LegacyID,
Customer = sageAccount.Customer
}
equals
new
{
LegacyID = consignments.ID,
Customer = true
}
select new { SageAccountID = sageAccount.ID };
Note that Property name, Type and order in the anonymous objects that you're joining on must match.
You can't use OR and AND in joins - use just equals one object to other.
This will have a this kind of result in your SQL:
SELECT [t0].[ID] AS [SageAccountID]
FROM [dbo].[SageAccount] AS [t0]
INNER JOIN [dbo].[Consignments] AS [t1] ON (([t0].[LegacyID]) = [t1].[ID])
AND ([t0].[Customer] = 1)

Conversion of Sql query to linq

I am trying to convert sql query for select to linq query using EF in MVC but really got stuck with an error.
In SQL I'm able to get 6 records for my query,similarly when I try to convert this to linq it shows some error.
Following is my query in SQL:
SELECT
PurchaseOrderMaster.*, PurchaseOrderDetails.*, Vendor.*,
BusinessUnit.*, InvoiceMaster.*, TenantEmployee.*
FROM
PurchaseOrderMaster
INNER JOIN
PurchaseOrderDetails ON PurchaseOrderMaster.TenantID = PurchaseOrderDetails.TenantID
AND PurchaseOrderMaster.PurchaseOrderNumber = PurchaseOrderDetails.PurchaseOrderNumber
AND PurchaseOrderMaster.PurchaseOrderDate = PurchaseOrderDetails.PurchaseOrderDate
INNER JOIN
InvoiceMaster ON PurchaseOrderMaster.TenantID = InvoiceMaster.TenantID
AND PurchaseOrderMaster.PurchaseOrderNumber = InvoiceMaster.PurchaseOrderNumber
AND PurchaseOrderMaster.PurchaseOrderDate = InvoiceMaster.PurchaseOrderDate
INNER JOIN
BusinessUnit ON PurchaseOrderMaster.TenantID = BusinessUnit.TenantID
AND PurchaseOrderMaster.BusinessUnitID = BusinessUnit.BusinessUnitID
INNER JOIN
TenantEmployee ON PurchaseOrderMaster.TenantID = TenantEmployee.TenantID
INNER JOIN
Vendor ON PurchaseOrderMaster.TenantID = Vendor.TenantID
AND PurchaseOrderMaster.VendorID = Vendor.VendorID
For this query I am able to get 6 records .
And my linq query is:
return (from pom in db.PurchaseOrderMaster
join pod in db.PurchaseOrderDetails on pom.TenantID equals pod.TenantID
where pom.PurchaseOrderNumber == pod.PurchaseOrderNumber && pom.PurchaseOrderDate == pod.PurchaseOrderDate
join inv in db.InvoiceMaster on pom.TenantID equals inv.TenantID
where pom.PurchaseOrderNumber == inv.PurchaseOrderNumber && pom.PurchaseOrderDate == inv.PurchaseOrderDate
join bu in db.BusinessUnit on pom.BusinessUnitID equals bu.BusinessUnitID
join te in db.TenantEmployee on pom.TenantID equals te.TenantID
join v in db.Vendor on pom.TenantID equals v.TenantID
where pom.VendorID == v.VendorID
orderby pom.PurchaseOrderNumber ascending, pom.PurchaseOrderDate descending
select new { pom, pod, inv, bu, te, v }).ToList();
At the time of debugging,following is the error that I'm getting:
{"Invalid column name 'invoiceMasterModel_TenantID'.\r\nInvalid column name 'invoiceMasterModel_PurchaseOrderNumber'.\r\nInvalid column name 'invoiceMasterModel_PurchaseOrderDate'.\r\nInvalid column name 'invoiceMasterModel_InvoiceNumber'.\r\nInvalid column name 'invoiceMasterModel_InvoiceDate'.\r\nInvalid column name 'tenantEmployeeModel_TenantID'.\r\nInvalid column name 'tenantEmployeeModel_EmployeeID'."}
Inside Invoice Table it is not able to find some of the columns and hence throwing the error according to me..
I tried with many possible ways but was unable to solve this.
Any ideas..?
Problem was with my Entity.
What I did is,I added my entity again and according to that I recreated models for the associated tables removing the earlier ones.
It solved my problem finally .
I found this link Entity Framework 5 Invalid Column Name error related to somewhat similar problem.
Here also similar kind of error happened after the date time field. Check if your datetime field PurchaseOrderDate is nullable.
Many tools exist that can convert your sql queries to linq, in case you don't wanna write it urself. Try the following sites, works well in my case:
http://www.sqltolinq.com/
http://www.linqpad.net/

SQL Server : INNER JOIN writes out things two times

Here is my SQL query
select
tblUnderKategori.fldKategori,
tblUnderKategori.fldNavn,
tblUnderKategori.fldBillede,
tblKategori.fldId,
tblKategori.fldKategoriNavn
from
tblUnderKategori
inner join
tblKategori on tblUnderKategori.fldKategori=2
And as you can see I need everything where my fldKategori = 2, and so it does, but it writes it out x2 times.
And here is my backend code for the place where it needs to be displayed
katFac objKat = new katFac();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack && !string.IsNullOrEmpty(Request.QueryString["id"]))
{
foreach (DataRow item in objKat.GetUnderkatByKat(Convert.ToInt32(Request.QueryString["id"])).Rows)
{
litUnderkategori.Text += item["fldNavn"].ToString() + "<br /><br />";
}
}
}
I just can't seeme to figure out the problem so anyone please help
Thank you in advance! :)
You are creating a karthesian product here as your join is missing the condition that actually joins the two tables together.
Try to use this:
select
tblUnderKategori.fldKategori,
tblUnderKategori.fldNavn,
tblUnderKategori.fldBillede,
tblKategori.fldId,
tblKategori.fldKategoriNavn
from
tblUnderKategori
inner join tblKategori
on tblUnderKategori.fldKategori = tblKategori.fldId
where tblUnderKategori.fldKategori=2
This assumes that tblUnderKategori.fldKategori contains the ID of the parent category.
A JOIN joins two tables, and you must provide the common column. If you also want to filter out certain values, add a WHERE clause afterwards. Also, you don't actually have to SELECT the fields used for matching and joining if you don't explicitly want to read them later on.
select
tblUnderKategori.fldNavn,
tblUnderKategori.fldBillede,
tblKategori.fldKategoriNavn
from tblUnderKategori join tblKategori
on tblUnderKategori.fldKategori = tblKategori.fldId
where
tblUnderKategori.fldKategori = 2
ON clause specifies on which column that tables should be joined, condition should be included in WHERE clause. Try Something like this:
SELECT
tblUnderKategori.fldKategori,
tblUnderKategori.fldNavn,
tblUnderKategori.fldBillede,
tblKategori.fldId,
tblKategori.fldKategoriNavn
FROM tblUnderKategori
INNER JOIN tblKategori
ON tblUnderKategori.[some key column] = tblKategori.[corresponding key column]
WHERE tblUnderKategori.fldKategori=2
You SQL statement is missing a field to JOIN the tables on. It should be something like this:
select u.fldKategori,
u.fldNavn,
u.fldBillede,
k.fldId,
k.fldKategoriNavn
from tblUnderKategori u
inner join tblKategori k
on u.fldKategori = k.fldId
where u.fldKategori=2
Then you will apply your filter in the the WHERE clause.

Categories