Linq Conditions .ANY() issues - linq

I am trying to do condition by comparing between dates. My class variables are like this is like this
public class SVCSpecialSchedule : BaseAuditEntity
{
public virtual int ID { get; set; }
public virtual string Name { get; set; }
public virtual string Description { get; set; }
public virtual IList<SVCSpecialScheduleList> SpecialScheduleList { get; set; }
public virtual IList<SpecialScheduleAssignment> SpecialScheduleAssignment { get; set; }
}
Now my Linq Query is below .
return _session.QueryOver<SVCSpecialSchedule>().Where
(sg => (sg.LastModifiedTimeStamp >= startDate
&& sg.LastModifiedTimeStamp <= endDate)
|| (sg.SpecialScheduleList.Any(ssl => ssl.LastModifiedTimeStamp >= startDate
&& ssl.LastModifiedTimeStamp <= endDate)
)
.List();
Now i am facing an issue like below
System.Exception
HResult=0x80131500
Message=Unrecognised method call: System.Linq.Enumerable:Boolean Any[SVCSpecialScheduleList](System.Collections.Generic.IEnumerable1[ServicesDomainModel.BOS.MerchandiseManagement.SVCSpecial.SVCSpecialScheduleList], System.Func2[ServicesDomainModel.BOS.MerchandiseManagement.SVCSpecial.SVCSpecialScheduleList,System.Boolean])
Source=NHibernate

Related

need to convert sql query to linq and return list of records

Hai using sql query its working database side, directly did not database because it code first approach. so i need following sql query convert to linq query. please any one suggest me .
SELECT Sy.SystemUserName,
MIN(Sc.CreatedOn) as StartedTime,
MAX(Sc.CreatedOn) as ExitTime,
datediff(MINUTE,
MIN(Sc.CreatedOn) ,
MAX(Sc.CreatedOn)) as WorkingHours
from SystemDetails Sy
LEFT JOIN Screenshots Sc on Sy.id = Sc.SystemId
where Sy.CompanyGUID = '25'
AND Sy.IsDeleted = 0
and (datediff(dd,Sc.CreatedOn,getdate()) = 0
Or SC.CreatedOn IS NULL)
GROUP By Sy.SystemUserName
SystemDetails Model :
public class SystemDetails
{
public int Id { get; set; }
[Required]
public string GuidID { get; set; }
[Required]
public string SystemUserName { get; set; }
[Required]
public string CompanyGUID { get; set; }
[Required]
public int TeamId { get; set; }
public User User { get; set; }
public ICollection<Screenshot> Screenshot { get; set; }
}
Screenshot Model :
public class Screenshot
{
public int Id { get; set; }
[Required]
public string GuidId { get; set; }
[Required]
public int SystemId { get; set; }
[Required]
public string Screenshotname { get; set; }
public DateTime CreatedOn { get; set; }
public string CreatedBy { get; set; }
public SystemDetails System { get; set; }
}
Return collection Class :
public class UserAttendance
{
public string StaffName { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public string WorkingHours { get; set; }
}
Here SystemDetails table Systemusername and Screenshot table CreatedOn fields we needed, SystemDeatils Id field and Screenshot SystemId field are key constraint. Need to get SystemUserName and Minimum CreatedOn date as StartTime, Maximum CreatedOn Date as EndTime. we get both datetime duration as WorkingHours. we have get all values using ef core. Incase CreatedOn date null or no date avilable then return '1900-01-01' default date. Please suggest me
Try this query:
var query =
from sy in dbContext.SystemDetails
from sc in sy.Screenshot
where sy.CompanyGUID == "25" && !sy.IsDeleted
&& (sc.CreatedOn == null || EF.Functions.DateDiffDay(sc.CreatedOn.Value, DateTime.Now) == 0)
group sc by new { sc.SystemUserName } into g
select new UserAttendance
{
StaffName = g.Key.SystemUserName,
StartTime = g.Min(x => x.CreatedOn.Value),
EndTime = g.Max(x => x.CreatedOn.Value),
WorkingHours = EF.Functions.DateDiffMinute(g.Min(x => x.CreatedOn.Value), g.Max(x => x.CreatedOn.Value)).ToString()
};

How i can LINQ select where? with Filters if Null Values

How i can do LINQ Querie.
List<ApplicationUser> ListaUsuarios = AccountControl.UserManager.Users.Where(i => i.Nombre == Filter.Nombre).ToList();
With many Filters when some attributs can coming with Null Value.
For example:
My FilterGeneric Class have many Attribute accept Nulls.
public class FilterGeneric
{
public DataCollectionType.FiltrosPdf Tipo { get; set; }
public string PdfTitle { get; set; }
public string pdfDescription { get; set; }
public string Nombre { get; set; }
public string Cargo { get; set; }
public string Iniciales { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public bool? Enabled { get; set; }
public DateTime? Date_since { get; set; }
public DateTime? Date_to { get; set; }
public string RoleName { get; set; }
public string Id_Sucursal { get; set; }
public string RUC { get; set; }
public string Direccion { get; set; }
public int? Direccion_Nro { get; set; }
public string Telefono { get; set; }
public int? Id_Localidad { get; set; }
}
Is that Possible? Thanks all for listening.
UPDATE:
I test with Answers
1#:
if (Filter.Nombre != null)
{
query = query.Where(i => i.Nombre == Filter.Nombre);
}
2#:
List<ApplicationUser> ListaUsuarios = AccountControl.UserManager.Users.Where
(x =>
(x.Nombre == Filter.Nombre || string.IsNullOrEmpty(Filter.Nombre)) &&
(x.Nombre == Filter.Cargo || string.IsNullOrEmpty(Filter.Cargo)) &&
(x.Nombre == Filter.Iniciales || string.IsNullOrEmpty(Filter.Iniciales)) &&
(x.Nombre == Filter.UserName || string.IsNullOrEmpty(Filter.UserName))
).ToList();
I get this Error:
You need to add all the filters one by one in the following manner:
List<ApplicationUser> ListaUsuarios =
AccountControl.UserManager.Users
.Where(
i =>
(i.Nombre == Filter.Nombre || string.IsNullOrEmpty(Filter.Nombre))
&&
(i.Cargo == Filter.Cargo || string.IsNullOrEmpty(Filter.Cargo))
).ToList();
This one is telling you, that if Filter.Nombre is null/empty just ignore it. Same case for Filter.Cargo and so on.
For nullable int
(Filter.Direccion_Nro == null || i.Direccion_Nro == Filter.Direccion_Nro.Value)
As the query gets materialized (means executed) when you call something that materializes it (.ToList(), ToArray() or a foreach for example), you can just chain them conditionally:
IEnumerable<ApplicationUser> query = AccountControl.UserManager.Users;
if(Filter.Nombre != null)
{
query = query.Where(i => i.Nombre == Filter.Nombre);
}
List<ApplicationUser> ListaUsuarios = query.ToList();
I think, you can perform it by using Reflection dynamically;
//Determine the not null properties of Filter object
var notNullProperties = Filter.GetType().GetProperties().Where(x => x.GetValue(Filter) != null).ToList();
//Perform where clause for not null properties of Filter
if (notNullProperties.Count > 0)
{
var ListaUsuarios = AccountControl.UserManager.Users.Where(x =>
notNullProperties.All(n => n.GetValue(Filter) == x.GetType().GetProperty(n.Name).GetValue(x))).ToList();
}

Linq Issue dealing with null values in select

I have the following entities in my solution
public class UtilityAccount : IObjectWithState
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid UtilityAccountID { get; set; }
public string Account { get; set; }
[ForeignKey("Person")]
public Guid PersonID { get; set; }
public virtual Person Person { get; set; }
public string ForeignID { get; set; }
[NotMapped]
public ObjectState ObjectState { get; set; }
public virtual ICollection<Utility> Utilities { get; set; }
public UtilityAccount()
{
Utilities = new List<Utility>();
}
}
public class Utility : IObjectWithState
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid UtilityID { get; set; }
[ForeignKey("UtilityAccount")]
public Guid UtilityAccountID { get; set; }
public virtual UtilityAccount UtilityAccount { get; set; }
public Guid? ServiceAddressID { get; set; }
[ForeignKey("ServiceAddressID")]
public virtual Address ServiceAddress { get; set; }
[NotMapped]
public ObjectState ObjectState { get; set; }
public double CurrentBalance { get; set; }
public double? PendingPaymentTotal { get; set; }
public string ForeignID { get; set; }
[ForeignKey("UtilityType")]
public Guid UtilityTypeID { get; set; }
public virtual UtilityType UtilityType { get; set; }
public virtual ICollection<UtilityBill> UtilityBills { get; set; }
public virtual ICollection<IncomingUtilityPayment> IncomingPayments { get; set; }
public Utility()
{
UtilityBills = new List<UtilityBill>();
IncomingPayments = new List<IncomingUtilityPayment>();
}
}
public class IncomingUtilityPayment : IObjectWithState
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid IncomingPaymentID { get; set; }
public string ForeignID { get; set; }
[ForeignKey("Utility")]
public Guid UtilityID { get; set; }
public virtual Utility Utility { get; set; }
public DateTime PaymentDate { get; set; }
public IncomingPaymentStatus IncomingPaymentStatus { get; set; }
public double? UtilityAmount { get; set; }
public double? ConvenienceFee { get; set; }
public double? TotalAmount { get; set; }
public string AuthCode { get; set; }
public string AuthReference { get; set; }
public string TenderType { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PaymentIdent { get; set; }
[NotMapped]
public ObjectState ObjectState { get; set; }
}
My problem is that I am trying to use Linq to retrieve information about a UtilityAccount and I am running into issues with the IncomingPayments for a Utility. Below is the select statement I am trying to use.
returnVal = repo.AllIncluding(o => o.Person, o => o.Utilities, o => o.Utilities.Select(p => p.UtilityType), o => o.Person.BillingAddress, o => o.Utilities.Select(p => p.ServiceAddress), o => o.Utilities.Select(p => p.IncomingPayments.Where(q => q.IncomingPaymentStatus == IncomingPaymentStatus.Pending || q.IncomingPaymentStatus == IncomingPaymentStatus.Processed )));
Everything ran fine until I added this clause to the statement.
o => o.Utilities.Select(p => p.IncomingPayments.Where(q => q.IncomingPaymentStatus == IncomingPaymentStatus.Pending || q.IncomingPaymentStatus == IncomingPaymentStatus.Processed ))
I think my issue ends up being something I am writing wrong in my Linq clause. The error I am getting is
The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties.
Parameter name: path
I can use the following statement with no issues
o => o.Utilities.Select(p => p.IncomingPayments)
as soon as I add the where clause in I get the error
I'm not familiar with EntityFramework nor linq-to-entities, but if it's just like linq-to-object you can:
add a .Where(p => p.IncomingPayments != null) before chaining with your .Select() like this
o.Utilities.Where(p => p.IncomingPayments != null)
.Select(p => p.IncomingPayments.Where(q => q.IncomingPaymentStatus == IncomingPaymentStatus.Pending || q.IncomingPaymentStatus == IncomingPaymentStatus.Processed))
The result will be a nested IEnumerable, i.e. IEnumerable<IEnumerable<IncomingUtilityPayment>>
If you actually need a IEnumerable<IncomingUtilityPayment> then .SelectMany() come in to play.
o.Utilities.Where(p => p.IncomingPayments != null)
.SelectMany(p => p.IncomingPayments)
.Where(q => q.IncomingPaymentStatus == IncomingPaymentStatus.Pending || q.IncomingPaymentStatus == IncomingPaymentStatus.Processed)
Hope this help

EF 4.1 POCO query

I have this POCO and I want to return a list of the users in a particular company.
public class Company
{
public AccreditedCompany()
{
this.Branches = new HashSet<Branch>();
}
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity), ScaffoldColumn(false)]
public int CompanyId { get; set; }
public bool Active { get; set; }
public virtual ICollection<Branch> Branches { get; set; }
}
public class Branch
{
public Branch()
{
this.Users = new HashSet<User>();
}
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity), ScaffoldColumn(false)]
public int BranchId { get; set; }
public int CompanyId { get; set; }
public string Name { get; set; }
public string ContactName { get; set; }
public virtual Company Company { get; set;}
public virtual ICollection<User> Users { get; set; }
}
public class User
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity), ScaffoldColumn(false)]
public int UserId { get; set; }
public int BranchId { get; set; }
public string ComputerSN { get; set; }
public string CameraSN { get; set; }
public virtual Branch Branch { get; set; }
}
This is my LINQ query:
var company = (from u in objDataContext.Companies.Include(c=>c.Branches.Select(v=>v.Users))
where u.CompanyId == 8 select u).FirstOrDefault();
IQueryable<User> users = (from j in company.Branches select j.Users);
I have this compilation error on the second query:
Error 2 Cannot implicitly convert type
'System.Collections.Generic.IEnumerable>'
to 'System.Linq.IQueryable'. An explicit conversion exists (are
you missing a cast?)
I want to get a list of the users, similar to a plain SQL statement like
SELECT dbo.Users.* FROM Branches
INNER JOIN dbo.Users ON dbo.Branches.BranchId = dbo.Users.BranchId
INNER JOIN dbo.Companies ON dbo.Branches.CompanyId = dbo.Companies.CompanyId
WHERE (dbo.Companies.CompanyId = 8)
Thanks in advance.
Your user query could be:
IEnumerable<User> users = company.Branches.SelectMany(branch => branch.Users);
This will return all users in any branch of the company.
It looks to me like you could just use:
IQueryable<User> users = objDataContext.Users
.Where(u => u.Branch.CompanyId == 8);
I notice you have both Company and CompanyId on your Branch entity, though. That seems redundant, even though it simplifies this query slightly. You should be able to get rid of Branch.CompanyId and User.BranchId and just use the entity associations.

LINQ query not returning all results due to null value on Entity Framework Core only

I have two rows of test data and am able to pull back the first row with no problems but can't get the second row to return. Digging around and testing shows that this is probably due to the AppovedByID column being null in the row that is not being returned. I have looked but can't figure out how to modify my LINQ query so it will return all rows even if the child table can't be linked in due to a null value.
The Query:
public JsonResult ChangeOrders()
{
var ChangeOrdersList = _DbContext.ChangeOrders
.Include(co => co.ApprovalStatus)
.Include(co => co.ApprovedBy)
.Include(co => co.AssignedTo)
.Include(co => co.CreatedBy)
.Include(co => co.CurrentStatus)
.Include(co => co.Impact)
.Include(co => co.Priority)
.Include(co => co.ChangeType)
.Select(co => new ChangeOrderListVM()
{
ApprovalStatus = co.ApprovalStatus.Name,
ApprovedBy = string.Concat(co.ApprovedBy.FirstName, ' ', co.ApprovedBy.LastName),
AssignedTo = string.Concat(co.AssignedTo.FirstName, ' ', co.AssignedTo.LastName),
CreatedBy = string.Concat(co.CreatedBy.FirstName, ' ', co.CreatedBy.LastName),
CurrentStatus = co.CurrentStatus.Name,
DateApproved = co.DateApproved,
DateCompleated = co.DateCompleated,
DateCreated = co.DateCreated,
DateStarted = co.DateStarted,
EstimatedEndDate = co.EstimatedEndDate,
EstimatedStartDate = co.EstimatedStartDate,
ID = co.ID,
Impact = co.Impact.Name,
Name = co.Name,
Priority = co.Priority.Name,
Reason = co.ReasonForChange,
Type = co.ChangeType.Name
}).ToList();
return Json(ChangeOrdersList);
}
ChangeOrders:
public class ChangeOrder
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public short? ApprovedByUserID { get; set; }
public byte ApprovalStatusID { get; set; }
public short AssignedToUserID { get; set; }
public short CreatedByUserID { get; set; }
public byte CurrentStatusID { get; set; }
public DateTime? DateApproved { get; set; }
public DateTime? DateCompleated { get; set; }
public DateTime DateCreated { get; set; }
public DateTime? DateStarted { get; set; }
public DateTime EstimatedStartDate { get; set; }
public DateTime EstimatedEndDate { get; set; }
public byte ImpactID { get; set; }
public byte PriorityID { get; set; }
public byte TypeID { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string ReasonForChange { get; set; }
[ForeignKey("ApprovalStatusID")]
public ChangeApprovalStatus ApprovalStatus { get; set; }
[ForeignKey("ApprovedByUserID")]
public User ApprovedBy { get; set; }
[ForeignKey("AssignedToUserID")]
public User AssignedTo { get; set; }
[ForeignKey("CreatedByUserID")]
public User CreatedBy { get; set; }
[ForeignKey("CurrentStatusID")]
public ChangeStatus CurrentStatus { get; set; }
[ForeignKey("ImpactID")]
public ChangeImpact Impact { get; set; }
[ForeignKey("PriorityID")]
public ChangePriority Priority { get; set; }
[ForeignKey("TypeID")]
public ChangeType ChangeType { get; set; }
}
Users:
public class User
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public short ID { get; set; }
[Required]
public string ADUserName { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string Email { get; set; }
[Required]
public string Phone { get; set; }
[Required]
public DateTime LastUpdated { get; set; }
}
EDIT:
This is apparently unique to Entity Framework 7 (AKA Core) as it works fine in EF 6. I am in fact using EF7 and as an additional test I updated a single line
ApprovedBy = string.Concat(co.ApprovedBy.FirstName, ' ', co.ApprovedBy.LastName),
and changed it to this
ApprovedBy = "",
and all the rows are returning so I then tried to do
ApprovedBy = (co.ApprovedByUserID.HasValue) ? string.Concat(co.ApprovedBy.FirstName, ' ', co.ApprovedBy.LastName) : "",
but that give a very odd error:
incorrect syntax near the keyword 'is'
This is a bug in the library. I have reported the bug for fixing in the next version on github

Resources