Why does my linq to sql query fail? - c#

I am new to .Net (and stackoverflow) so I am running into a few problems. One vexing problem is this linq query below. Some information about the code. CustomerCart is a separate Model class in my project where the products member is a list of products. If I remove the products from the select new CustomerCart portion it runs fine and the data is present. So I figure it is my syntax. Can I not put a linq statement inside an assignment constructor? Any help would be appreciative. Thank you in advance.
var k = from s in store.Customers
join p in store.ShoppingCarts on s.custId equals p.customerId
select new CustomerCart()
{
FirstName = s.firstName,
LastName = s.lastName,
products = (from j in store.Products
where p.productId == j.productId
select j).ToList(),
CartID = p.cartId,
CustomerID = s.custId,
};
**Edit
Error I receive: The model item passed into the dictionary is of type 'System.Data.Objects.ObjectQuery`1[productShop.Models.CustomerCart]', but this dictionary requires a model item of type 'productShop.Models.CustomerCart'.
Sorry for not placing the error message with my question.

Try this query instead:
var k =
from s in store.Customers
join p in store.ShoppingCarts on s.custId equals p.customerId
join j in store.Products on p.productId equals j.productId into products
select new CustomerCart()
{
FirstName = s.firstName,
LastName = s.lastName,
products,
CartID = p.cartId,
CustomerID = s.custId,
};

Related

Combining 2 select statement and join sql

I'm currently having a problem on sql statement
here's my code
SELECT [Cities].ProvinceId,[Cities].Name,[Provinces].Name
FROM [Cities] JOIN Provinces
ON [Cities].ProvinceId = [Provinces].id
UNION
SELECT [Regions].RegionName,[Countries].CountryName
FROM [Regions] JOIN Countries
ON [Regions].RegionId = [Countries].RegionId
so basically what I am trying to do is that get the cities,province,region and countries.
I have 4 regions by the way which is
ASEAN = 1,ASIA = 2,WORLDWIDE = 3,DOMESTIC = 4
so DOMESTIC needs to be on the cities and province only because they are places local here in my country
and regions 1,2,3 are for countries but I could join theme because of these error
All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.
by the way I Applied it like this on my API
var provinces = await _provinceRepository.GetAll();
var cities = await _cityRepository.GetAllCities();
var result = provinces.Join(cities, p => p.Id, c => c.ProvinceId, (p, c) =>
new DestinationModel
{
Region = null,
City = c.Name,
State = p.Name,
Continent = null,
Country = null
}).ToList();
return Ok(result);
Now you can see my problem is that for now I can only get provinces and cities
the region and country are still null. Could someone help me with my query.
so basically what I am trying to do is that get the cities,province,region and countries.
Does this do what you want?
SELECT c.Name as city, p.Name as province, co.name as country,
r.name as region
FROM Cities c
JOIN Provinces p ON c.ProvinceId = p.id
JOIN Countries co ON p.CountryId = co.id
JOIN Regiones r ON co.RegionId = r.id;
To me, it seems like a more sensible result.

LINQ Join gives only first result multiple times

I have this Join :
var mycust= db.CUSTOMER.Where(x => x.NAME.Contains(nameid)).ToList();
var CancCustomer = (from cust in myCust
join ip in db.IPS on must.ID equals ip.CUSTOMER_ID
select new JoinObj {ID = cust.ID, NAME = cust.NAME, LASTNAME = cust.LASTNAME,
TYPE_ID = ip.TYPE_ID, TYPE2_ID = ip.TYPE2_ID,
SERVICE_ID = ip.SERVICE_ID , REASON = ip.REASON }).ToList();
This code returns the first linq result multiple times? What am I missing? Thanks.
Instead of Where, you should use SingleOrDefault/Single - these would indeed return a single row into your mycust variable.
SingleOrDefault would put a null into the variable if no such customers were found (and assuming a Customer is a reference type - if it were a value type, it would be the default value for the type). Single would throw an exception if no items were found or more than one were found, which could be very useful in finding errors in your data (such as duplicate customer records).
Additionally, it is likely your ip table has multiple matching records for a customer - which is why you would be seeing multiple records being returned from your select.
You have multiple Duplicate Record received Then Try For following quires
var mycust= db.CUSTOMER.Where(x => x.NAME.Contains(nameid)).ToList();
var CancCustomer = (from cust in myCust
join ip in db.IPS on cust.ID equals ip.CUSTOMER_ID
select new JoinObj {ID = cust.ID, NAME = cust.NAME, ASTNAME=cust.LASTNAME, TYPE_ID = ip.TYPE_ID, TYPE2_ID = ip.TYPE2_ID, SERVICE_ID = ip.SERVICE_ID , REASON = ip.REASON }).distinct().ToList();
Other Wise Multiple record then You Get One Record for You following Query
var mycust= db.CUSTOMER.Where(x => x.NAME.Contains(nameid)).ToList();
var CancCustomer = (from cust in myCust
join ip in db.IPS on must.ID equals ip.CUSTOMER_ID
select new JoinObj {ID = cust.ID, NAME = cust.NAME, LASTNAME = cust.LASTNAME, TYPE_ID = ip.TYPE_ID, TYPE2_ID = ip.TYPE2_ID, SERVICE_ID = ip.SERVICE_ID , REASON = ip.REASON }).distinct().FirstOrDefault();

Left outer join off of group by dataset using linq

I am attempting to write the following SQL as a linq query.
SELECT grp.OrganisationId,
grp.OrderCount,
organisations.Name
FROM (select OrganisationId,
count(*) as OrderCount
from orders
where 1 = 1
group by OrganisationId) grp
LEFT OUTER JOIN organisations on grp.OrganisationId = organisations.OrganisationId
WHERE 1 = 1
The where clauses are simplified for the benefit of the example.
I need to do this without the use of navigational properties.
This is my attempt:
var organisationQuery = ClientDBContext.Organisations.Where(x => true);
var orderGrouped = from order in ClientDBContext.Orders.Where(x => true)
group order by order.OrganisationId into grouping
select new { Id = grouping.Key.Value, OrderCount = grouping.Count() };
var orders = from og in orderGrouped
join org in organisationQuery on og.Id equals org.Id
select(x => new OrganisationOrdersReportPoco()
{
OrganisationNameThenCode = org.Name,
TotalOrders = og.OrderCount
});
But I am getting an error of...
Type inference failed in the call to 'Join'
From previous threads, I believe this is because I have "lost the join with order" (but I don't understand why that matters when I am creating a new recordset of Organisation, Count).
Thanks!
I understand you may believe navigation properties are the solution here, but if possible, please can we keep the discussion to the join off of the group by as this is the question I am trying to resolve.
You are mixing lambda and LINQ expressions. Change select to:
select new OrganisationOrdersReportPoco()
{
OrganisationNameThenCode = org.Name,
TotalOrders = og.OrderCount
};
If i understood your model correctly you could try this instead:
var orders = ClientDBContext.Organisations.Select(org => new OrganisationOrdersReportPoco
{
OrganisationNameThenCode = org.Name,
TotalOrders = org.Orders.Count()
}).ToList();

Linq with Lambda equivalent of SQL

I am relatively new to entity framework and I've been trying to write a Linq statement with Lambda that includes a simple join. I have three tables: Staff - StaffRole - Role.
I want a staff member in a certain role that satisfies a certain condition. Its very simple to write this in regular SQL:
SELECT *
FROM Staff s
INNER JOIN StaffRole sr ON s.StaffId = sr.StaffId
INNER JOIN Role r ON sr.RoleId = r.RoleId
WHERE r.Description = 'SpecialisedHealthManager'
AND s.PrimaryShm = 0
Now, writing it in a Linq statement has not given me much luck. I'm thinking it would be something like this:
var actingShm = db.Staff.Join(db.StaffRole,
inner => inner.StaffId,
outer => outer.Role,
(outer, inner) => new
{
StaffId = inner.StaffId,
FirstName = inner.Staff.FirstName,
Surname = inner.Staff.Surname,
SamAccountName = inner.Staff.SamAccountName,
RoleId = outer.Description
});
Needless to say, this is not working..
Try using it this way:
var list = from s in Staff
join sr in StaffRole on s.StaffId equals sr.StaffId
join r in Role on sr.RoleId equals r.RoleId
where r.Description == 'SpecialisedHealthManager' && s.PrimaryShm == 0
select new
{
StaffId = s.StaffId,
FirstName = s.Staff.FirstName,
Surname = s.Staff.Surname,
SamAccountName = s.Staff.SamAccountName,
RoleId = r.Description
});
Look here if you realy want to do this with method syntax LINQ:
SO Multiple tables join with lambdas
Also look here:
http://msdn.microsoft.com/pl-pl/library/bb534675(v=vs.110).aspx
for Join extension method syntax. Usage presented in your code is wrong.
You should have your associations setup so you can do this...
var actingShm = from s in db.Staff
from r in s.Roles
where r.Description == "SpecialisedHealthManager"
select new
{
StaffId = s.StaffId,
FirstName = s.FirstName,
Surname = s.Surname,
SamAccountName = s.SamAccountName,
RoleId = r.Description
});
Are you using Entity Framework or Linq2SQL?

LinqToSql: Select field from list used within a query

I perform a query on a table Installation to get a list of Ids that are needed to query a table Product on a different database (before you ask, it has to be this way, can't query across dbs). Here's what the list looks like:
class Installation
{
Guid InstallationId
Guid ProductId
}
List<Installation> installs;
I don't have any problems using this list for the query in to the Product table which looks like this:
var prods = (from p in context.Product
where installs.Select(i => i.ProductId).Contains(p.ProductId)
select new
{
ProductNumber = p.ProductNumber
// How do I get InstallationId from installs??
}).ToList();
What I need to know is how I can retrieve InstallationId from the list and store it in the new list?
Thanks in advance.
You should do a join
var products = (from product in context.Product
join install in installs
on install.ProductId equals product.ProductId
select new {
ProductNumber = product.ProductNumber
InstallationId = install.InstallationId
}
).ToList();
A slight refactoring of Jason's answer to allow for the LinqToSql exception.
var products = (from product in context.Product
where installs.Select(i => i.ProductId).Contains(p.ProductId)
select product).ToList()
var installedProducts = (from product in products
join install in installs
on install.ProductId equals product.ProductId
select new
{
ProductNumber = product.ProductNumber,
InstallationId = install.InstallationId
}).ToList();

Categories

Resources