does not contain a definiton for where for linq - mysql

I want to query from Users table with linq query. I am getting an error on this line on "Users.Where";
var KisiList = Users.Where(w => w.Userstatus == 1 && w.Isactive == 1).ToList();
Users does not contain a definiton for where. what should I add here?
public List<Users> GetBagliOlduguKisiList()
{
var KisiList = Users.Where(w => w.Userstatus == 1 && w.Isactive == 1).ToList();
List< Users> users= new List< Users>();
foreach (var item in KisiList )
{
Users par= new Users();
par. ID= item. ID;
par. Name= item. Name;
users.Add(par);
}
return users;
}

Probably you have missed using System.Linq;. Also if you are using LINQ, try to do that effectively and retrieve only needed fields.
public List<Users> GetBagliOlduguKisiList()
{
var users = Users
.Where(w => w.Userstatus == 1 && w.Isactive == 1)
.Select(u => new Users
{
ID = u.ID,
Name = u.Name
})
.ToList();
return users;
}

Related

Convert complex nested selects in Entity Framework query

I need to create a table in View by this View Model:
public class ApplicationContentViewModel
{
public BPMSPARS.Models.MySql.application application {get; set;}
public BPMSPARS.Models.MySql.content content { get; set; }
public BPMSPARS.Models.MySql.app_delegation app_delegation { get; set; }
}
But the query for creating new Table is very complex.
I use this query in MySQL, and I can get correct results by using it.
SELECT APP_UID, (SELECT CON_VALUE FROM content WHERE CON_CATEGORY = 'PRO_TITLE' AND CON_ID =
(SELECT PRO_UID from app_delegation WHERE del_thread_status='open' and USR_UID = '00000000000000000000000000000001' AND APP_UID = '9134216305aaaea1b67c4e2096663219')) AS TASK_NAME,
(SELECT CON_VALUE FROM content WHERE CON_CATEGORY = 'TAS_TITLE' AND CON_ID =
(SELECT TAS_UID from app_delegation WHERE del_thread_status='open' and USR_UID = '00000000000000000000000000000001' AND APP_UID = '9134216305aaaea1b67c4e2096663219')) AS PROCESS_NAME FROM app_delegation
WHERE del_thread_status='open' and USR_UID = '00000000000000000000000000000001' AND APP_UID = '9134216305aaaea1b67c4e2096663219'
But, I have to convert this query in linq or EF in MVC.
How Can I write This Query in Entity Framework query?
And How Can I display results in View?
Your SQL query seems (very) peculiar to me, as it is quite redundant. I am going to assume the sub-queries return a single value and enforce it with LINQ.
First I pulled out the common sub-query over app_delegation:
var USR_APP_Delegation = from a in app_delegation
where a.del_thread_status == "open" &&
a.USR_UID == "00000000000000000000000000000001" &&
a.APP_UID == "9134216305aaaea1b67c4e2096663219"
select a;
In LINQ it is easy to combine the two UID queries into one query:
var UIDs = (from a in USR_APP_Delegation
select new { a.PRO_UID, a.TAS_UID })
.Single();
Now you can do the name subqueries:
var TASK_NAME = (from c in content
where c.CON_CATEGORY == "PRO_TITLE" &&
c.CON_ID == UIDs.PRO_UID
select c.CON_VALUE)
.Single();
var PROCESS_NAME = (from c in content
where c.CON_CATEGORY == "TAS_TITLE" &&
c.CON_ID == UIDs.TAS_UID
select c.CON_VALUE)
.Single();
Then you can put all the queries together for the final result:
var ans = (from a in USR_APP_Delegation
select new {
a.APP_UID,
TASK_NAME,
PROCESS_NAME
})
.Single();
Again, this makes it obvious that your e.g. returning APP_UID when you know exactly what it is, and you are combining TASK_NAME and PROCESS_NAME into a query for no real advantage.
I would suggest using join against content makes a much more understandable query (even in SQL) and makes it clearer what is being returned:
var names = from a in app_delegation
join cpro in content on new { CON_ID = a.PRO_UID, CON_CATEGORY = "PRO_TITLE" } equals new { cpro.CON_ID, cpro.CON_CATEGORY }
join ctas in content on new { CON_ID = a.PRO_UID, CON_CATEGORY = "TAS_TITLE" } equals new { ctas.CON_ID, ctas.CON_CATEGORY }
where a.del_thread_status == "open" &&
a.USR_UID == "00000000000000000000000000000001" &&
a.APP_UID == "9134216305aaaea1b67c4e2096663219"
select new {
a.APP_UID,
Task_Name = ctas.CON_VALUE,
Process_Name = cpro.CON_VALUE
};

LINQ to SQL: rows to columns

I would like to have a single LINQ to SQL query to count 2 entities from the same table. E.g. Count number of employees and managers from table Personnel.
Example:
var q = from p in db.Personnel
where p.PersonType == 'Manager' || p.PersonType == 'Employee'
select new
{ NoOfPersonnel = p.Count(p => p.PersonType == 'Employee'), //Wrong way
NoOfManagers = p.Count(p => p.PersonType == 'Manager') //Wrong way
}
How can I do it?
Try this:
var list = from employee in db.Personnel
where employee.PersonType == "Manager" || employee.PersonType == "Employee"
group employee by employee.PersonType
into temp
select new { PersonType = temp.Key, Count = temp.Count() };

How to write Linq-To-SQL statment which is equal to my following TSQL?

TSQL:-
Update table1
Set Name = 'John',
Address = null
where
ID = 1
LINQ-TO-SQL
var tab = db.Table1.Single(s => s.ID == 3);
tab.Name = DateTime.Now;
tab.Address = null;
db.SubmitChanges();
There isn't a single LINQ to SQL statement for updates. You have to retrieve the object, modify it, then save the changes (code assumes a single row since you have a specific Id):
var entity = context.Table1.Single(t => t.Id == 1);
entity.Name = "John";
entity.Address = "Toronto";
context.SubmitChanges();
using (var dataContext = new MyEntities())
{
var contact = Contacts.Single (c => c.ContactID == 1);
contact.FirstName = 'John';
contact.Address= 'Toronto';
dataContext.SaveChanges();
}

LINQ join and group

How to expand this query:
public Dictionary<int, List<TasksInDeal>> FindAllCreatedTasks()
{
return (from taskInDeal in db.TasksInDeals
where taskInDeal.Date > DateTime.Now && taskInDeal.Date < DateTime.Now.AddDays(7)
group taskInDeal by taskInDeal.CreatedByUserID
into groupedDemoClasses
select groupedDemoClasses).ToDictionary(gdc => gdc.Key, gdc => gdc.ToList());
}
into something like this:
public Dictionary<int, List<TaskForNotification>> FindAllCreatedTasks()
{
return (from taskInDeal in db.TasksInDeals
join user in db.Users on taskInDeal.CreatedByUserID equals user.UserID
where taskInDeal.Date > DateTime.Now && taskInDeal.Date < DateTime.Now.AddDays(7)
group taskInDeal by taskInDeal.CreatedByUserID
into groupedDemoClasses
select new TaskForNotification
{
Email = user.Email,
TaskInDealField1 = taskInDeal.TaskInDealField1,
TaskInDealField2 = taskInDeal.TaskInDealField2,
TaskInDealField3 = taskInDeal.TaskInDealField3,
...
}
).ToDictionary(gdc => gdc.Key, gdc => gdc.ToList());
}
So, to first query I need to join email from other table.
// do the date logic up front, not in the database.
DateTime now = DateTime.Now
DateTime weekFromNow = now.AddDays(7);
// pull the joined rows out of the database.
var rows =
(
from taskInDeal in db.TasksInDeals
where taskInDeal.Date > now && taskInDeal.Date < weekFromNow
join user in db.Users
on taskInDeal.CreatedByUserID equals user.UserID
select new {TaskInDeal = taskInDeal, UserEmail = user.Email}
).ToList();
// shape the rows in memory
Dictionary<int, List<TaskForNotification>> result =
(
from row in rows
let taskForNotification = new TaskForNotification
{
Email = row.UserEmail,
TaskInDealField1 = row.TaskInDeal.TaskInDealField1,
TaskInDealField2 = row.TaskInDeal.TaskInDealField2,
TaskInDealField3 = row.TaskInDeal.TaskInDealField3,
...
}
group taskForNotification by row.TaskInDeal.CreatedByUserID
// without an "into", group by ends the query.
).ToDictionary(g => g.Key, g => g.ToList());
When you group, bear this in mind. Groups in SQL have only keys and aggregates. Groups in LINQ have keys, aggregates and elements! If you ask the database for groups, and then ask for the elements - SQL couldn't provide you with those elements in a single query. You'll wind up automatically repeatedly re-querying using the group's key as a filter.

Linq to SQL question - specifying columns then modifying column

I'm trying to write a linq to sql method that handles sorting, paging, and filtering for an ajax grid. I created a partial class Employee that has a TotalRecordCount, as I need to pass this to the javascript for setting up the pager. The problem is that it won't build because I can't set the AnonymousType#1.TotalRecordCount, it's read-only. Yet if I do "select new Employee", then it will throw the Exception - "Explicit construction of entity type 'InVision.Data.Employee' in query is not allowed.".
Here's the code...
public string GetPageJSON(string sortColumn, string sortDirection, int pageNumber, int pageSize, EmployeeSearch search)
{
var query = from e in db.Employees
select new
{
EmployeeID = e.EmployeeID,
FirstName = e.FirstName,
LastName = e.LastName,
LoginName = e.LoginName,
IsLockedOut = e.IsLockedOut,
TotalRecordCount = e.TotalRecordCount
};
//searching.
if (search.FirstName.Length > 0) query = query.Where(e => e.FirstName.Contains(search.FirstName));
if (search.LastName.Length > 0) query = query.Where(e => e.LastName.Contains(search.LastName));
if (search.LoginName.Length > 0) query = query.Where(e => e.LoginName.Contains(search.LoginName));
if (search.Status.Length > 0) query = query.Where(e => (search.Status == "Active" && !e.IsLockedOut)
|| (search.Status == "Inactive" && e.IsLockedOut));
//sorting.
query = query.OrderBy(sortColumn, sortDirection);
//get total record count.
int totalRecordCount = query.Count();
//paging.
query = query.Skip((pageNumber - 1) * pageSize).Take(pageSize);
//set total record count.
var list = query.ToList();
if (list.Count > 0)
{
list[0].TotalRecordCount = totalRecordCount; //throws exception
}
//return json.
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(list);
}
You'll want to select the original objects rather than mapping them to new objects (whether of the same type, or an anonymous type).
Replace this:
var query = from e in db.Employees
select new
{
EmployeeID = e.EmployeeID,
FirstName = e.FirstName,
LastName = e.LastName,
LoginName = e.LoginName,
IsLockedOut = e.IsLockedOut,
TotalRecordCount = e.TotalRecordCount
};
With this:
var query = db.Employees.AsQueryable();
Then later on replace this:
var list = query.ToList();
if (list.Count > 0)
{
list[0].TotalRecordCount = totalRecordCount;
}
With this:
var list = from e in query
select new
{
EmployeeID = e.EmployeeID,
FirstName = e.FirstName,
LastName = e.LastName,
LoginName = e.LoginName,
IsActive = !e.IsLockedOut,
TotalRecordCount = totalRecordCount
};
I think that should be everything. If the JavaScriptSerializer requires a List, just make sure you use it like this: return serializer.Serialize(list.ToList());
I ended up using a custom view class to get this to work...
partial class EmployeeView
{
public int EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string LoginName { get; set; }
public bool IsActive { get; set; }
public int TotalRecordCount { get; set; }
}
public string GetPageJSON(string sortColumn, string sortDirection, int pageNumber, int pageSize, EmployeeSearch search)
{
var query = from e in db.Employees
select new EmployeeView
{
EmployeeID = e.EmployeeID,
FirstName = e.FirstName,
LastName = e.LastName,
LoginName = e.LoginName,
IsActive = !e.IsLockedOut,
TotalRecordCount = 0
};
//searching.
if (search.FirstName.Length > 0) query = query.Where(e => e.FirstName.Contains(search.FirstName));
if (search.LastName.Length > 0) query = query.Where(e => e.LastName.Contains(search.LastName));
if (search.LoginName.Length > 0) query = query.Where(e => e.LoginName.Contains(search.LoginName));
if (search.Status.Length > 0) query = query.Where(e => (search.Status == "Active" && e.IsActive)
|| (search.Status == "Inactive" && !e.IsActive));
//sorting.
query = query.OrderBy(sortColumn, sortDirection);
//get total record count.
int totalRecordCount = query.Count();
//paging.
query = query.Skip((pageNumber - 1) * pageSize).Take(pageSize);
//set total record count.
var list = query.ToList();
if (list.Count > 0)
{
list[0].TotalRecordCount = totalRecordCount;
}
//return json.
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(list);
}