I have a general understanding issue of Linq as it seems. I tried already to find the answer in other threads but was not successful.
Why does this query not work ? I have two tables: one with customer data, the other with order data and try now to join them. But it fails and I don't understand yet why ? In my opinion it is done as in any other tutorial.
IEnumerable<DataRow> query = from cust_ in Cust.AsEnumerable()
join order_ in Orders.AsEnumerable() on cust_.Field<int>("ID") equals order_.Field<int>("Customer ID")
select new { customer = cust_.Field<string>("LastName") }
This is the error meassge it throws:
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<<anonymous type: System.Data.DataRow cust_, System.Data.DataRow order_>>' to 'System.Collections.Generic.IEnumerable<System.Data.DataRow>'. An explicit conversion exists (are you missing a cast ?
Your select is not returning a DataRow, it's returning an anonymous type. Either drop the 'new' and return a string,
IEnumerable<string> query = from cust_ in Cust.AsEnumerable()
join order_ in Orders.AsEnumerable() on cust_.Field<int>("ID")
equals order_.Field<int>("Customer ID")
select cust_.Field<string>("LastName")
or maybe better don't specify the type, instead try:
var query = from cust_ in Cust.AsEnumerable()
join order_ in Orders.AsEnumerable() on cust_.Field<int>("ID")
equals order_.Field<int>("Customer ID")
select new { customer = cust_.Field<string>("LastName") }
Related
I have this LINQ query:
myDataObject.period = (from pe in myDataObject.myEDMXDataObject.MyTable
join product in myDataObject.products
on pe.ID equals product.ID
where pe.LangID == myDataObject.chosenLang.LangID
select pe).Distinct().ToList();
where myDataObject.products is of type
List<MyDataObject> products;
I get myDataObject.products with a similar LINQ query with join and where clauses, like this
myDataObject.products = (from tbl in MyTableName
join tbl2 in MyTableName2
on tbl1.ID equals tbl2.ID
where /* where conditions here */
select tbl).ToList();
It works properly. But I want to keep my code clean so instead of running all those conditions and the join again, I want to pass the data I have found already into the next LINQ query.
I am getting error like this:
A first chance exception of type 'System.NotSupportedException' occurred in System.Data.Entity.dll
with inner exception:
Unable to create a constant value of type 'MyWPFApp.MyTableName'. Only primitive types or enumeration types are supported in this context.
Of course, the error is clear, I am doing something which is not allowed.
How can I send result from one LINQ query as a part of another LINQ query?
You are using a JOIN when what you should be using is a WHERE:
// select the distinct IDs
var productIds = myDataObject.products.Select(x => x.ID).Distinct().ToList();
myDataObject.period = myDataObject.myEDMXDataObject.MyTable
.Where(pe => pe.LangID == myDataObject.chosenLang.LangID
&& productIds.Contains(pe.ID))
.Distinct()
.ToList();
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/
I'm quite new to entity framework and I'm trying to use the join clause on two entities as follows.
var alertlist = from elogAlert in yangkeeDBEntity.Yang_Kee_Logistics_Pte_Ltd_ELog_Tablet_Alert
where elogAlert.No_ != null
join elogAlertDetail in yangkeeDBEntity. Yang_Kee_Logistics_Pte_Ltd_ELog_Tablet_Alert_Details
on elogAlert.No_ == elogAlertDetail.AlertID
where elogalertdetail.employee_id == driverid
select new
{
elogalertdetail.employee_id,
elogalertdetail.alert_id,
elogalertdetail.no_,
elogalertdetail.status,
elogalertdetail.created_by,
elogalertdetail.date_created,
};
Hi from the above code I'm getting two errors saying
'Error 1 The name 'elogAlertDetail' is not in scope on the left side of 'equals'. Consider swapping the expressions on either side of 'equals'.' and 'linq joint type inference failed to call 'join' error '
Currently the two tables does not have any data. Ill be happy if anyone can help me with this situation
you cant use == when joining with Linq. You need to use equals.
Note that it is not the method .Equals(..) but the keyword
from elogAlert in yangkeeDBEntity.Yang_Kee_Logistics_Pte_Ltd_ELog_Tablet_Alert
join elogAlertDetail in yangkeeDBEntity.Yang_Kee_Logistics_Pte_Ltd_ELog_Tablet_Alert_Details
on elogAlert.No_ equals elogAlertDetail.AlertID //this line has equals instead of ==
where elogAlert.No_ != null
where elogalertdetail.employee_id == driverid
select new
{
elogalertdetail.employee_id,
elogalertdetail.alert_id,
elogalertdetail.no_,
elogalertdetail.status,
elogalertdetail.created_by,
elogalertdetail.date_created,
};
Look at the documentaion on Linq join
The error you have relates to the order of arguments around the equals operand on join.
The joined table MUST be the RHS of the equals, and the LHS must be in the row you are joining to.
In this instance yangkeeDBEntity is not in the elogAlert row
CF the example in MSDN
from c in categories
join p in products on c equals p.Category into ps
from p in ps
select new { Category = c, p.ProductName };
c is in the row you are joining from, p.category is on the table you are joining to
in addition you also need to use the word equals not == as mentioned above
What is wrong with this code ?
I got this exception on the last line:
Unable to create a constant value of
type
'System.Collections.Generic.IEnumerable`1'.
Only primitive types ('such as Int32,
String, and Guid') are supported in
this context.
var query = from colT in dal.TBL_Gharardad
select colT;
if(lstTarafeGharardadIds.Count>0)
query = from q in query
join id in lstTarafeGharardadIds on q.TarafeGharardadId equals id
select q;
dgvListeGharardad.DataSource = query.ToList();
The lastTarafeGharardadIds is a List<int>
I also test
dgvListeGharardad.DataSource = query;
Everything works well if if expression equals to false and this code
query = from q in query
join id in lstTarafeGharardadIds on q.TarafeGharardadId equals id
select q;
doesn't run. But I can't understand I got the error on the last line (on this code):
dgvListeGharardad.DataSource = query.ToList();
I think linq can't join between an in-memory collection (lstTarafeGharardadIds) and a database table (dal.TBL_Gharardad, dal.v_Gharardad...).
Similar problem: Why won't this LINQ join statement work?
This should work:
var query = (from colT in dal.TBL_Gharardad select colT).AsEnumerable();;
if (lstTarafeGharardadIds.Count>0)
query = from q in query
join id in lstTarafeGharardadIds on q.TarafeGharardadId equals id
select q;
dgvListeGharardad.DataSource = query.ToList();
Wow, thats hard to read!
Anyways, assuming your naming convention is right. you end up with: select colV. Selecting a column results in selecting a IEnumerable rather then a primitive value which your dataSource requires.
You can try and use SelectMany to select the actual value you need
dgvListeGharardad.DataSource = query.SelectMany(x => x.[YourProperty]).ToList();
Sorry about the vague title, not sure what verbage I should be using. I have a query similar to this (re-worked to save space):
SELECT
*
FROM
Publishers p
INNER JOIN Authors a
ON p.AuthorID = a.AuthorID
INNER JOIN Books b
ON a.BookID = b.BookID
WHERE
p.PublisherName = 'Foo'
ORDER BY
b.PublicationDate DESC
I tried to re-write it as such:
var query =
from publisher in ctx.Publishers
from author in publisher.Authors
from books in author.Books
...
but got the following error:
Error 1 An expression of type 'Models.Books' is not allowed in a
subsequent from clause in a query expression with source type
'System.Linq.IQueryable<AnonymousType#1>'. Type inference failed in the
call to 'SelectMany'.
I can re-write the LINQ to make it work by just joining the tables, as I would in SQL, but I thought I could accomplish what I want to do by their relationships - I'm just a bit confused why I can get publisher.Authors, but not author.Books.
Check that you have a relationship in your DB from Authors to Books.
Try this...
var result = (from pItem in ctx.Publishers
join aItem in ctx.Authors on pItem.AuthorId equals aItem.AuthorId
join bItem in ctx.Books on pItem.BookId equals bItem.BookId
where pItem.PublisherName== "Foo"
select new {
// Fields you want to select
}
).ToList();
i don't know exact relationship of the tables but you can an idea from this one.