MVC3 select int value through LINQ - asp.net-mvc-3

I am trying to get customerId from Customer table.
However, when I try to make it, it has error said, 'Cannot implicitly convert type 'System.Linq.Iqueryable' to 'int''
How can I get customerId??
Thank you.
Here is my coding.
int customerId = from a in db.Customer
where a.userName == customerName
select a.customerId;
//it has error in here.
order.customerId = customerId;

It's possible that your query could return multiple rows. You need to tell LINQ that you only want the first (or a single) result:
int customerId = (from a in db.Customer
where a.userName == customerName
select a.customerId).First();

I like using the .Single() function when I know there should be only one row.
int customerId = (from a in db.Customer
where a.userName == customerName
select a.customerId).Single();
This throws an exception if more or less than one row is found, which is sometimes useful depending on your situation.

use it this way:
var customer = db.Customer.FirstOrDefault(c =>c.userName == customerName)
var id = customer.Id
Select returns an IEnumerable, so you can't convert it to int.

There is one more suggestion I can recommend for this question is to use First or default.
var customerId = (from a in db.Customer
where a.userName == customerName
select a.customerId).FirstOrDefault();
order.customerId = customerId; this should now work fine since it already knows it int

Related

Transform Sql to EF Core Linq query

I am trying to translate the following query from SQL to EF Core. I can easily just use a stored procedure (I already have the SQL), but am trying to learn how some of the linq queries work. Unfortunately this is not by any means an ideal database schema that I inherited and I don't have the time to convert it to something better.
DECLARE #userId INT = 3
SELECT *
FROM dbo.CardGamePairs
WHERE EXISTS (SELECT 1
FROM dbo.Users
WHERE Users.Id = CardGamePairs.player1Id
AND Users.userId = #userId)
UNION
SELECT *
FROM dbo.CardGamePairs
WHERE EXISTS (SELECT 1
FROM dbo.Users
WHERE Users.Id = TableB.player2Id
AND Users.userId = #userId)
So basically I have an id that can exist in one of two separate columns in table b and I don't know in which column it may be in, but I need all rows that have that ID in either column. The following is what I tried to make this work:
//Find data from table A where id matches (part of the subquery from above)
var userResults = _userRepository.GetAllAsQueryable(x => x.userId == userId).ToList();
//Get data from table b
var cardGamePairsResults = _cardGamePairsRepository.GetAllAsQueryable(x => userResults .Any(y => y.userId == x.player1Id || y.userId == x.player2Id));
When I run the code above I get this error message:
predicate: (y) => y.userId == x.player1Id || y.userId == x.player2Id))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync().
Any ideas on how I can make this work? (I tried changing the column and table names to something that would actually make sense, hopefully I didn't miss any spots and make it more confusing.)
Because you are already have user id use it to query both columns.
var userResults = _userRepository
.GetAllAsQueryable(x => x.userId == userId)
.ToList();
var cardGamePairsResults = _cardGamePairsRepository
.GetAllAsQueryable(x => x.player1Id == userId || x.player2Id == userId));

How to select different fields using .Concat for Union All query

I’m doing some preliminary work getting data consumption ready from a webAPI controller in MVC. I’m using a linq query that mimics a union query that uses two joins. However, I need the select statement to ask for a different field on each side of the union. This works fine in SSMS when I run the query, but when I create the query in linq it will not allow the fields to be different. It gives an error saying that each anonymous type requires a receiver of the same type. This is referring to the two anonymous types created via select new { }… Here’s the two queries.
In SQL:
Select m.Last_Name, first_name, m.dc_number, Dept_Job as JobOrStatus FROM
Master_Roster m
INNER JOIN Class_Assignment a on m.dc_number = a.dc_number
where a.subject_am = 'y1'
AND Start_Date_AM <= '1/31/18'
UNION ALL
Select m.Last_Name, first_name, m.dc_number, status_am FROM Master_Roster m
INNER JOIN Attend_am_y1 at on m.dc_number = at.dc_number
where at.class_date_am >= '1/1/18'
AND at.class_date_am <= '1/31/18'
ORDER BY Last_Name
In linq:
(from m in db.Master_Roster
join c in db.Class_Assignment
on m.dc_number equals c.dc_number
orderby m.Last_Name
where c.Subject_AM == "y1"
select new { m.dc_number, m.Last_Name, m.First_Name }).Concat(
from m in db.Master_Roster
join a in db.attend_am_y1 on m.dc_number equals a.dc_number
orderby m.Last_Name
where a.class_date_am >= date1 &&
a.class_date_am <= date2
select new { m.dc_number, m.Last_Name, m.First_Name });
If I were to add dept_job and status_am to the linq query, it throws aforementioned error. I’d like to do this without using a stored procedure. Any ideas?
Instead of putting into 2 anonymous types, put into the same viewmodel and concat. Eg:
Internal Class ConcatViewModel{
public int DcNumber {get;set;}
public string LastName {get;set;)
// etc...
}
Then:
select new ConcatViewModel{
DcNumber = m.dc_number,
LastName = m.Last_Name,
FirstName = m.First_Name,
Status = m.Dept_Job
}
and
select new ConcatViewModel{
DcNumber = m.dc_number,
LastName = m.Last_Name,
FirstName = m.First_Name,
Status = m.status_am
}
(assuming that status_am and Dept_Job are the same underlying type)

How to query dataset table on primary key of smallInt using linq C#

Let say I have the following sql table. Customer_id column is a primary key with smallint.
And I am trying to create a linq query, where I want to get all data for customer with id, let say 1.
How to do this.
Already done and not working:
1.
var query = from row in dt.AsEnumerable()
where row.Field<Int32>("customer_id") == Convert.ToInt32(2)
select row;
2.
var query = from row in dt.AsEnumerable()
where row.Field<Int16>("customer_id") == Convert.ToInt16(2)
select row
debug for example 1,2
Syntax error
Exceptions
Why don't you use this:
DataRow needle = hayStack.Tables["Customer"].Rows.Find(2);
Your method should be rewritten as something like this:
private DataRow GetCustomerDetails(Int16 customer_id)
{
return _dt.Tables["Customer"].Rows.Find(customer_id);
}
The calling method would have to check for null beeing returned from the method, since an invalid customer_id would cause Find() tu return null.
Try using short type instead of Int32.

Can I use this query in the entity 4.0 framework?

I'm needing some syntax help with the following query please? I'd like to use an equivalent in the entity framework but I'm unsure of the syntax.
Can someone help me format this to work with the entity framework?
Thanks in advance.
Select * from (
SELECT [Member]
,[MemberGroup],
(SELECT [text]
FROM [umbracoNode]where [id] = [Member]) As MemberName,
(SELECT [text]
FROM [umbracoNode]where [id] = [MemberGroup]) As GroupName
FROM [cmsMember2MemberGroup]
) UG
where UG.MemberName is not null
order by UG.MemberName,
UG.GroupName
Try this:
var query =
from x in db.cmsMember2MemberGroup
join y in db.umbracoNode on x.Member equals y.id
let MemberName = y.text
where MemberName != null
join z in db.umbracoNode on x.MemberGroup equals z.id
let GroupName = z.text
orderby new { MemberName, GroupName }
select new
{
x.Member,
x.MemberGroup,
MemberName,
GroupName,
};
Is there a particular reason that this query is in this format?
Why are there not use of joins?
Need to really understand what you want here first and get into better sql before going to linq.

How to Query and count an Employees table and Project table in one linq query in silverlight?

I have two tables an employee table and a project table and I am looking to bring back a count of the number of employees assigned to each project. In the employee table I have employeeIDs and projectIDs, and in the projects table I have projectID, name, department, notes, etc. I am looking to bring back the following information and display it in one single DataGrid in silverlight with the number of employees assigned to each project as a Count.
Name Department Notes Count
There are many ways to do this, but the simplest is probably to do it like this:
var x =
from proj in db.Projects
select new
{
Name = proj.Name,
Department = proj.Department,
Notes = proj.Notes,
Count = db.Employees.Where(emp => emp.ProjectID == proj.ProjectID).Count()
};
Alternatively, if you created a foreign key between Projects and Employees on ProjectID (if not, you should strongly consider doing so), LINQ will kindly provide even cleaner syntax:
var x =
from proj in db.Projects
select new
{
Name = proj.Name,
Department = proj.Department,
Notes = proj.Notes,
Count = proj.Employees.Count()
};
It doesn't get any better than that!
I think you want something like this....
dbContext dbCon = new dbContext();
var projects = from project in dbCon.Projects
join employee in dbCon.Employees on project.ProjectID equals employee.projectid
group employee by new { employee.projectid, project.Name, project.Department, project.Notes } into grouping
select new {
//projectID = grouping.Key.projectid,
projectName = grouping.Key.Name,
projectDepartment = grouping.Key.Department,
projectNotes = grouping.Key.Notes,
count = grouping.Count()
};

Resources