LinQ Grouping records with null values - linq

I have a table and need to get list by grouping Field1 and Field2
public class Journal
{
public int ID {get; set;}
public string DateField { get; set; }
public string Notes { get; set; }
public int Field1 { get; set; }
public string Field2 { get; set; }
}
First of all I filter data by Field2 (string) and when grouping by two fields (Field1 and Field2)
MyList = DBContext.Journals.Where(f=>f.Field2.StartsWith(someParam))
.GroupBy(g => new { g.Field1, g.Field2 })
.Select(n=> n.Key.Field1).ToList();
If Field1 and Field2 is not null, everything is ok, but how to solve a problem if they are null, could You help?
If there are nulls, I got an exception:
"The cast to value type 'System.Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type."

have you tried maybe with something like:
MyList = DBContext.Journals.Where(f=> !String.IsNullOrEmpty(f.Field1) && f.Field2 != null && (f.Field2.StartsWith(someParam)))
.GroupBy(g => new { g.Field1, g.Field2 })
.Select(n=> n.Key.Field1).ToList();

Related

RavenDB using filter with group by

I have a Transaction entity.
I can make group by by (CustomerCode, CustomerName) then select CustomerCode and Total(Amount).
It is easy. But When I Want to filter AtCreated. I have An Error.
Unhandled exception. Raven.Client.Exceptions.InvalidQueryException: Raven.Client.Exceptions.InvalidQueryException: Field 'AtCreated' isn't neither an aggregation operation nor part of the group by key
Query: from Transactions group by CustomerCode, CustomerName where AtCreated >= $p0 select CustomerCode, count() as Total
Parameters: {"p0":"2019-01-01T00:00:00.0000000"}
public class Transactions
{
public string Id { get; set; }
public long TransId { get; set; }
public DateTime AtCreated { get; set; }
public string CustomerCode { get; set; }
public string CustomerName { get; set; }
public string City { get; set; }
public double Amount { get; set; }
public string GXF { get; set; }
}
var transactList = session.Query<Transactions>()
.Where(a=>a.AtCreated >= new DateTime(2019,01,01))
.GroupBy(a => new {a.CustomerCode, a.CustomerName})
.Select(a => new {a.Key.CustomerCode, Total = a.Count()})
.ToList();
How can I Grouping filtered data?
Thank You.
Create a Map-Reduce Index and then query on it.
https://ravendb.net/docs/article-page/4.2/csharp/indexes/map-reduce-indexes
For example, in this example, you can query on 'Category' field because it was indexed (meaning it was part of the Map-Reduce index definition)
See short demo examples in:
https://demo.ravendb.net/

Add the child to the nested field of the parent document in elastic search

I want to create a parent child relationship in document in elastic search. But the child document should reference the nested field value see below.
PUT DemoIndex/_doc/1
{
"Name":"XYX",
"ClassGrads":[
{"I":"A"},
{"II","A"},
{"III","A"},
{"IV","A"},
{"V","A"},
]
}
So I want to map the child document with the item of ClassGrads and keep DemoIndex as parent document.
public class Parent
{
public string Field1 { get; set; }
public string Field2 { get; set; }
public List<DemoClass> Field3 { get; set; }
}
public class DemoClass
{
public int Id { get; set; }
}
public class ChildClass
{
public string Field1 { get; set; }
public string Field2 { get; set; }
}
So child document will be mapped to the Id of the demo class. This is the problem statement
Based on the POCO I have create the index as below.
var indexResponse = elasticClient.CreateIndex("parentindex", s => s
.Index<Parent>()
.Mappings(ms => ms
.Map<Parent>(m => m
.RoutingField(r => r.Required())
.AutoMap<Parent>()
.AutoMap<ChildClass>()
.Properties(prop => prop
.Join(j => j
.Name(p => p.Field3 .FirstOrDefault().Id)
.Relations(r => r
.Join<Parent, ChildClass>()
)
)
)
)
)
);
Is there is anything I am missing here ?
Because I got the index creation response as valid but when I am going to see the mappings it says index not created.

Entity framework is making the id null on insert

I'm getting the following error when I try to insert a new row in one of my relational tables. I have the following two models:
public class CompanyCredit
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int creditId { get; set; }
public int planCredit { get; set; }
public DateTime? PlanCreditExpirationDate { get; set; }
}
And
public class CompanyInformation
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
[Required]
[DisplayName("Company Name:")]
public string companyName { get; set; }
public string timeZone { get; set; }
//navigation Properties
public virtual CompanyCredit Credits { get; set; }
}
And this Relation in the dbContext
modelBuilder.Entity<CompanyInformation>().HasOptional(e => e.Credits);
I'm trying to add a record inside CompanyCredit table like so:
if (_company.Credits == null)
{
var _credits = new CompanyCredit();
_credits.planCredit = 200;
_credits.PlanCreditExpirationDate = System.DateTime.UtcNow.AddMonths(1);
_company.Credits = _credits;
repo.InsertOrUpdate(_company, User.Identity.Name);
}
And Finally Insert or update just marks Company as changed and _credit as added like so:
_db.Entry(_credits).State = System.Data.EntityState.Added;
_db.Entry(Company).State = System.Data.EntityState.Modified;
_db.SaveChanges();
When this runs I get the following Error that I just can't seem to find the reason to.
Cannot insert the value NULL into column 'creditId', table 'Project.dbo.CompanyCredits'; column does not allow nulls. INSERT fails.
The statement has been terminated.
Thank in advanced for your help.
I found the problem was in the attribute [DatabaseGenerated(DatabaseGeneratedOption.Identity)] this should have been [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
I thought I would post this so others might benefit from it.
Could you please try reversing the order of entity state modification, just before the saveChanges call
_db.Entry(Company).State = System.Data.EntityState.Modified;
_db.Entry(_credits).State = System.Data.EntityState.Added;
_db.SaveChanges();

When a parameter is null, Linq fails while creating projection list

I am trying to get a list of MemberMaintenanceData objects through Linq as shown below. The problem is, whenever m.StartDate is null it is throwing NullObjectReference error.
var filteredMembers = from m in members.ToList()
select new MemberMaintenanceData
{
MemberName = m.Name,
SSN = m.SSN,
PlanName = m.PlanName,
EffectiveDate = m.StartDate ?? null,
//EffectiveDate = m.StartDate ?? DateTime.Now,
GroupName = ""
};
public class MemberMaintenanceData
{
public string MemberName { get; set; }
public string SSN { get; set; }
public string PlanName { get; set; }
public DateTime? EffectiveDate { get; set; }
public string GroupName { get; set; }
}
In the MemberMaintenanceData EffectiveDate is declared as nullable and I am checking whether it is null or not. Strangely EffectiveDate = m.StartDate ?? DateTime.Now line works fine. Please let me know how to resolve it.
Thanks
I just ran a repro and it works as expected. I don't think that StartDate is the issue here. I think you misinterpret where the NullReferenceException is coming from.
My guess is that your members list contains a null reference.

Linq sub collection criteria where collection is a list of doubles

If I have a couple of classes like this ;
public class Employee
{
public string Name { get; set; }
public string Address { get; set; }
public double Salary { get; set; }
public List<Salary> PastSalaries { get; set; }
}
public class Salary
{
public double Amount { get; set; }
}
I can get a list of employees who have had a past salary that was less than a certain amount ; eg
var employees = employeeList.Where(o => o.PastSalaries.Any(p => p.Amount < 35000));
this works fine, but if my past salaries collection wasn't a collection of Salary classes but rather a collection of doubles. eg
public class Employee
{
public string Name { get; set; }
public string Address { get; set; }
public double Salary { get; set; }
**public List<double> PastSalaries { get; set; }**
}
then how can i do the same query as before?
var employees = employeeList.Where(o => o.PastSalaries.Any(???? < 35000));
What do I do my comparison against?
Thanks,
var employees = employeeList.Where(o => o.PastSalaries.Any(p => p < 35000));
The parameter to the delegate is now a double, not a Salary type with an Amount property, so you can compare on the parameter directly.
var employees = employeeList.Where(o => o.PastSalaries.Any(p=>p < 35000));
Try this. In first case your type is Salary and you check Amount field of that type.
In this case you want to check double value ,so p<35000 will work properly.

Resources