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/
Related
I am incorporating a SQL Server query in C# and using a RDLC report to show query results. My query produces the correct result when run on SQL Server, but I get an error
Conversion failed when converting date/time from character string
when using it from C# code. I could not figure out why got this error. Please help me
C# code:
DateTime Date =DateTime.Parse(d2.Value.Date.ToString());
string format = "yyyy-MM-dd";
MessageBox.Show(Date.ToString(format));
this.soldItemsDetailsTableAdapter.Fill(this.Daily_Sales_Report.SoldItemsDetails, Date.ToString(format));
The error occurs on the last line of this code.
Date stored in database in format 'yyyy-MM-dd' and the above code produces date format as required as confirmed by the following code:
MessageBox.Show(Date.ToString(format));
SQL Server query:
SELECT
b.CompanyID, b.Category, a.ModelNo, a.ProductCode, a.Qty
FROM
(SELECT
s.DateSold, p.ProductID, p.ModelNo, p.ProductCode,
SUM(sipl.SubTotal) AS Qty
FROM
SalesInvoiceProductsList AS sipl
INNER JOIN
SalesInvoice AS s ON sipl.SalesInvoiceID = s.SalesInvoiceID
INNER JOIN
Product AS p ON sipl.ProductID = p.ProductID
GROUP BY
p.ModelNo, p.ProductCode, p.ProductID, s.DateSold) AS a
INNER JOIN
(SELECT DISTINCT
p.ProductID, p.CompanyID, cat.Category
FROM
Product AS p
INNER JOIN
Category AS cat ON p.CatID = cat.CatID
INNER JOIN
Company AS c ON p.CompanyID = c.CompanyID) AS b ON a.ProductID = b.ProductID
WHERE
(a.DateSold = #Date)
ORDER BY
b.CompanyID
If I use simple query which also takes date input instead of this complex query then got NO error. However his complex query works fine on SQL Server.
I resolved the issue by changing nothing except the query. Both queries executes well on server but the integration of first query issue the error under discussion but the following query does not issue any error, although the date format is same in both queries. I could not understand the reason. Can anybody explain why?
SELECT com.CompanyID AS company, c.Category, p.ModelNo AS Model, (sipl.SubTotal) AS Qty
FROM SalesInvoiceProductsList AS sipl
INNER JOIN SalesInvoice AS s ON sipl.SalesInvoiceID = s.SalesInvoiceID
INNER JOIN Product AS p ON sipl.ProductID = p.ProductID
INNER JOIN Company AS com ON p.CompanyID = com.CompanyID
INNER JOIN Category AS c ON p.CatID = c.CatID
WHERE (s.DateSold = #Date)
GROUP BY com.CompanyID, c.Category, p.ModelNo,sipl.SubTotal
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();
Below is the SQL Query I am trying to translate
SELECT dbo.Contracts.Supplier
FROM dbo.Contracts INNER JOIN dbo.Products ON dbo.Contracts.Product = dbo.Products.Product
where dbo.Products.ProductGroup='Crude'
GROUP BY dbo.Contracts.Supplier
Am I doing something wrong because I do not get same results with the following LINQ
var result = from c in context.Contracts
join p in context.Products on c.Product equals p.Product1
where p.Product1.Equals("Crude")
group c by c.Supplier into g
select new { supplier = g.Key };
It is generating a weird statement
SELECT
1 AS [C1],
[Distinct1].[Supplier] AS [Supplier]
FROM ( SELECT DISTINCT
[Extent1].[Supplier] AS [Supplier]
FROM [dbo].[Contracts] AS [Extent1]
WHERE N'Crude' = [Extent1].[Product]
) AS [Distinct1]
Using distinct would work but to get same results, LINQ should be generating a statement like so (it's like it is ignoring the join):
SELECT distinct dbo.Contracts.Supplier
FROM dbo.Contracts INNER JOIN dbo.Products ON dbo.Contracts.Product = dbo.Products.Product
where dbo.Products.ProductGroup='Crude'
I'm assuming that you are using 'EntityFramework' or 'Linq To SQL'. If so, you should be able to use navigation properties to navigate to product and filter invalit results out. This way your query might look something like this:
var result = (from c in context.Contracts
where c.Products.Any(p => p.ProductGroup == "Crude")
select c.Supplier).Distinct();
It will automatically convert into correct query (in this case possibly without join even, just using Exists sql keyword) and return distinct suppliers. This is if I understand your objective correctly - you want to obtain all suppliers assigned to contracts that contain product from 'Crude' product group.
Basically you should try to avoid using joins from linq to sql or linq to entities as much as possible when you can use navigation properties. System will probably be better at converting them into specific sql.
I have a LINQ query (using with EF)
Basically I want to add a column in Select results based on value of another column.
I have PaymentDate column in DB table but not Paid column. If there is null in PaymentDate column it also shows payment is false and if it has some date in it means paid is true.
Here is my query, please guide me how to do that.
var selectedResults=
from InvoiceSet in Invoices
join BookedAreasSet in BookedAreas
on InvoiceSet.InvoiceID equals BookedAreasSet.InvoiceID
join AreaSet in Areas on BookedAreasSet.AreaID equals AreaSet.AreaID
select new {InvoiceSet.InvoiceNumber,InvoiceSet.Amount,InvoiceSet.TotalDiscount,InvoiceSet.GST, InvoiceSet.PaymentDate,InvoiceSet.ShoppingCentreID,BookedAreasSet.BookedAreaID,
AreaSet.Name,Here I want to add calculated value column based on InvoiceSet.PaymentDate value}
I think you should be able to do something like this
var selectedResults=
from InvoiceSet in Invoices
join BookedAreasSet in BookedAreas
on InvoiceSet.InvoiceID equals BookedAreasSet.InvoiceID
join AreaSet in Areas on BookedAreasSet.AreaID equals AreaSet.AreaID
select new { InvoiceSet.InvoiceNumber,InvoiceSet.Amount,InvoiceSet.TotalDiscount,InvoiceSet.GST,
InvoiceSet.PaymentDate,InvoiceSet.ShoppingCentreID,BookedAreasSet.BookedAreaID,
AreaSet.Name,Paid = (InvoiceSet.PaymentDate == null) }
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.