Find all the different persons that appear in the table charged with the responsible entity that creates a connection more or more persons and entities projects?
how to convert sql query in there technologies?
Sql query is
select distinct p.PersonID,p.FirstName,p.LastName
from Responsible tr inner join People p on p.PersonID=tr.People_PersonID;
My attemot is
string query = #"SELECT value empl
FROM TicketBaseEntities.Responsible AS tr
INNER JOIN TicketBaseEntities.People AS empl
on empl.PersonID =tr.Responsibles.People_PersonID where tr.Responsibles !=null";
return Context.CreateQuery<Employee>(query).Distinct();
Error message is:
'People_PersonID' is not a member of 'Transient.collection[TicketBaseModel.Person(Nullable=True,DefaultValue=)]'. To extract a property of a collection element, use a subquery to iterate over the collection. Near simple identifier, line 5, column 63.
(from tr in Responsible
join from p in People on tr.People_PersonID equals p.PersonID
select p.PersonID,p.FirstName,p.LastName).Distinct()
You can Implement IComparer interface to use Distinct() function for Class People
Related
I've three tables:
Car
Parts
SubParts
Now I want to get data from all the three tables, which is easy by performing inner join I can easily get that. My SQL query is
Select C.Id AS CarId,C.Name AS CarName
, P.Id AS PartsId,P.Name AS PartsName
, SP.Id AS SubPartsId,SP.Name AS SubPartsName
from Car C
INNER JOIN Parts P on C.Id=P.CarId
INNER JOIN SubParts SP on P.Id=SP.PartsId
In C# I've same entities with same properties as that of table columns and the same name as that of the table, now I want to populate data from a single query in three different entities without iterating each record returned from SQL query. Is there any that can be done in using ADO.NET or Enterprise Library(more preferable).
Use the join from LINQ.
var innerJoinQuery =
from car in cars
join part in parts on car.Id equals part.CarId
join subPart in subParts on part.Id equals subPart.PartId
select new {
CarId = car.Id,
CarName = car.Name,
PartsId = part.Id,
PartsName = part.Name,
SubPartsId = subPart.Id,
SubPartsName = subPart.Name
};
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 am using Linq to SQL in Linqpad to get to some data.
I have 3 tables I need to use to do the following steps:
1) Select customers by postcode (Customer table)
2) Get all transaction ID's for these customers (Transaction table)
3) Get itemized items for all transaxction ID's (Itemized table)
So i start out easy enough and grab the customers:
string pc = "123";
var cust =
from c in Customers
where c.PostCode.StartsWith(pc) == true
select c;
Now I need to create a new Linq object that has the lookup from transaction table based on the "CustomerID" field but I am not sure how to do this. Ive experimented with some foreach loops but cant get syntax right. Did some googling and saw posts saying not to use foreach loops with linq objects as you should use inbuilt Linq functionality but I couldnt find any examples doing what I needed.
I apologise for such a basic question but I have just started using Linq.
How do I create the next Linq object with all transaction records based on the CustoomerID field?
You can use single query with joins. If you have navigation properties in your entities:
from c in Customers
from t in c.Transactions
from i in t.ItemizedItems
where c.PostCode.StartsWith(pc)
select i
Labda syntax:
Customers.Where(c => c.PostCode.StartsWith(pc))
.SelectMany(c => c.Transactions)
.SelectMany(t => t.ItemizedItems);
If you don't have navigation properties:
from c in Customers
join t in Transactions on c.ID equals t.CustomerID
join i in t.ItemizedItems on t.ID equals i.TransactionID
where c.PostCode.StartsWith(pc)
select i
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.
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.