EF and LINK query not giving all table values in "select" - linq

How do I use a column in the "where" that I haven't inluded in the "select"? The "where" method isn't showing me all the columns in my SQL Server table, only the 3 in the select statement. I need to do the select based on a different column in the table:
using (var context = new URIntakeEntities())
{
return context.Claims.Select(
u => new Models.Claim
{
ClaimNumber = u.ClaimNumber,
DateOfInjury = u.DateOfInjury,
Denied = u.Denied
}).Where(u => u.?????).ToList();
}

You should move your where statement before the select statement.
using (var context = new URIntakeEntities())
{
return context.Claims.Where(u=> u.?????).Select(
u => new Models.Claim
{
ClaimNumber = u.ClaimNumber,
DateOfInjury = u.DateOfInjury,
Denied = u.Denied
}).ToList();
}

How do I use a column in the "where" that I haven't included in the
"select"?
You can't. Where is applied on a current type of sequence. So, you should apply filter before projecting result:
using (var context = new URIntakeEntities())
{
return context.Claims
.Where(u => u.?????)
.Select(u => new Models.Claim
{
ClaimNumber = u.ClaimNumber,
DateOfInjury = u.DateOfInjury,
Denied = u.Denied
}).ToList();
}

Related

How to count distinct

I'm implementing ASP.NET Core project and have a query like the following for finding count of distinct userId per operatorName, however it shows me error for the line count distinct after running the project:
var activeUserPerOperatorCount = requests.GroupBy(x => new { operatorName = x.Operator.Name, x.UserId }).Select(x => new
{
userIds = x.Key.UserId,
operatorNames = x.Key.operatorName,
activeUserPerOperatorCount = x.Select(l => l.UserId).Distinct().Count()
}).ToList();
I appreciate if anyone helps me how can I find distinct count of userId per operatorName in my query.
ok, the correct query is like the following and it works correctly:
var activeUserPerOperatorCount = requests.GroupBy(x => new { operatorName = x.Operator.Name}).Select(x => new
{
operatorNames = x.Key.operatorName,
activeUserPerOperatorCount = requests.Select(l => l.UserId).Distinct().Count()
}).ToList();

How can I add Sum from another Table in my Model?

So I have my View setup like this in the controller:
public ActionResult View(Guid projectID)
{
OnboardModel model = context.onboard_projectInfos.Where(x => x.projectID == projectID).Select(x =>
new OnboardModel()
{
propertymanagername = x.propertymanagername,
propertymanagercontactemail = x.propertymanagercontactemail,
date_modified = (DateTime)x.date_modified,
projectmanagercontactnumber = x.projectmanagercontactnumber,
Developer = x.onboard_projectCreate.Developer,
status1 = x.onboard_projectCreate.status1,
ProjectName = x.onboard_projectCreate.ProjectName
}).SingleOrDefault();
var pix = projectID.ToString();
context.onboard_BuildingInfos.Where(x => x.buildprojectID == pix).GroupBy(x => x.buildprojectID).Select(g => {
model.totalres = g.Sum(b => b.numberofres);
model.totalcom = g.Sum(b => b.numberofcommer);
});
return View(model);
}
Problem is grabbing the sum of numberofres and numberofcommer from BuildingInfos.
Using .Select gives me the error:
Error CS0411 The type arguments for method 'Queryable.Select(IQueryable, Expression>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
How to I write this LINQ statement correctly?
Thanks.
You cannot modify an object within a select (you can only create a new object). Further, you can't add new properties to an existing object.
We'll assume that OnboardModel defines the totalres and totalcom properties.
var query = context.onboard_BuildingInfos
.Where(x => x.buildprojectID == pix)
.GroupBy(x => x.buildprojectID);
foreach(var g in query)
{
model.totalres = g.Sum(b => b.numberofres);
model.totalcom = g.Sum(b => b.numberofcommer);
}

How to write LINQ query as one query?

I have the following query that groups locations and the average item cost and I would like to write it as one query but I cannot figure out the syntax. What LINQ do I need to do this? I have tried writing it different ways but the syntax is not correct.
var joinedData =
from r in shops
join i in items on r.shopId equals i.shopId
select new
{
Region = r.Location,
ItemCost = i.ItemCost
};
var AverageCostByLocation = joinedData
.GroupBy(m => new { m.Location})
.Select(m => new
{
Location= m.Key.Location,
AverageItemCost = m.Average(x => x.ItemCost)
});
Well, if you put first expression in parenthesis it should allow to join both expressions as they are. Also I'd probably get rid of second anonymous type for perfomance reasons (the new { m.Location} line is redundant, you might want to use .Key instead) :
var AverageCostByLocation =
(from r in shops
join i in items on r.shopId equals i.shopId
select new
{
Region = r.Location,
ItemCost = i.ItemCost
})
.GroupBy(m => m.Location)
.Select(m => new
{
Location= m.Key,
AverageItemCost = m.Average(x => x.ItemCost)
});

LINQ to Entities does not recognize the method 'Boolean HasFlag(System.Enum)' method, and this method cannot be translated into a store expression

I have this service:
//seroiunoiweucroewr
///wercewrwerwerwer
//wcererewrwerwer
public List<UserRoleContract> GetRolePagesByUserId(long plngUserId, DisplayType displayType)
{
List<UserRoleContract> result = new List<UserRoleContract>();
using (CitiCallEntities context = new CitiCallEntities())
{
try
{
//var DisplayList = Utility.GetEnumDescriptions(typeof(DisplayType)).ToList();
//var selectValue = DisplayList.Where(i => i.Key == (byte) DisplayType.Windows).FirstOrDefault();
result = (from oUser in context.User
join oUserRole in context.UserRole on oUser.Id equals oUserRole.UserId
join oRoleRightsPage in context.RoleRightsPage.Where(i => i.IsActive == true)
on oUserRole.RoleId equals oRoleRightsPage.RoleId
join oApplicationPage in context.ApplicationPage.Where(i => i.IsActive == true)
on oRoleRightsPage.PageId equals oApplicationPage.Id
join oRole in context.Role on oUserRole.RoleId equals oRole.Id
join oEmployee in context.Employee on oUser.EmployeeId equals oEmployee.Id
join oSection in context.Section on oEmployee.SectionId equals oSection.Id
where oUser.IsActive == true && oUser.Id == plngUserId
&& oRole.IsActive == true && (((DisplayType)oRoleRightsPage.DisplayType).HasFlag(displayType))
//am getting error in has flag
// am having three display type web, windows and all
// how to overcome
select new UserRoleContract
{
UserId = oUser.Id,
RoleId = oRole.Id,
RoleName = oRole.RoleName,
PageID = oApplicationPage.Id,
PageName = oApplicationPage.PageName,
IsOPsCtrl = oRole.IsOPsCtrl,
ISOPsCtrlFor = oRole.OPsCtrlFor,
SectionId = oSection.Id,
DisplayType = oRoleRightsPage.DisplayType,
}).Distinct().ToList();
}
catch (Exception exception)
{
HandleExpcetion(exception);
//throw new CitiCallException(exception.Message);
}
}
return result;
}
I am getting Linq error in has flag conversion, how do I overcome this problem?
you are geeting error because HasFlag method is not paresent in database i.e. it might be part of language or local function in code which is not present in database.
So when query is translated it found this method is not available and that is the reason you are getting error.
one solution to avoid this error is
Brind all data from databae
Than filter than data, i.e. apply HasFlag method of it.
But this will bring all data and might decrease performance.
Example is
remove this line (((DisplayType)oRoleRightsPage.DisplayType).HasFlag(displayType) from your query
var list = querieddata //first fetch data without hasflag condition/method
.AsEnumerable() // Rest of the query in-process
.Where(oRoleRightsPage=> ((DisplayType)oRoleRightsPage.DisplayType).HasFlag(displayType))//apply condition here once fetching done
.ToList();
The HasFlag method has no equivalent in Linq to Entities which is why you get that error. You can get around it by using bitwise comparison instead of using HasFlag, for example this:
((DisplayType)oRoleRightsPage.DisplayType).HasFlag(displayType)
Becomes:
(oRoleRightsPage.DisplayType & displayType) > 0

Replacing empty values with a default value in a Linq to Entities query

In the Linq to Entities query below I need to place a default value in the x.Number in the returned value if the query returns 0 OfficeTelephone objects. I have tried
x.Number??"555-1212" but that throws an error.
from c in Contacts
.Where(a => a.LastName.Contains("ANDUS")).Take(10)
select new
{
Id = c.Id,
OfficeTelephone = c.Telephones.Where(a=>a.TelephoneType.Name.Contains("Office")).Select(x => new { x.AreaCode, x.Number, x.TelephoneType, x.Primary })
}
I've tried something like:
from c in Contacts
.Where(a => a.LastName.Contains("ANDUS")).Take(10)
select new
{
Id = c.Id,
OfficeTelephone = c.Telephones
.Where(a=>a.TelephoneType.Name.Contains("Office"))
.Select(x => new { x.AreaCode, x.Number, x.TelephoneType, x.Primary })
.DefaultIfEmpty()}
But I'm not sure how to push a default object into the DefaultIFEmpty()
Use DefaultIfEmpty and pass a default instance with those value which you would want by default i.e. if no rows are returned.
try it like this:
Contacts.Where(a=>a.LastName.Contains("ANDUS"))
.Take(10)
.Select(x => new
{
Id = x.Id,
OfficeTelephone = x.Telephones
.Where(a=> a.Telephone.Name.Contains("Office"))
.Select(b=> new Telephone
{
b.AreaCode,
b.Number,
b.TelephoneType,
b.Primary
})
.DefaultIfEmpty(new Telephone())
});
where I've assumed that typeof(x.Telephones) == typeof(List<Telephone>)

Resources