Issue with querying database using LINQ query to bring list of DTO - sql

I have a LINQ query in the below format. The problem is that I am passing a list of 100 consumerID in the form of list. I want to query the database and bring result for
all these 100 consumerIds. However the query brings back the result only for the first guy. I am suspecting I am missing something in the where clause. I am sure there are matching results in the database for all these 100 consumerIds.
public ICollection<ConsumerExchangeChangeDto> GetByConsumers(List<int> consumerIDs)
{
EnrollmentReportingModel db = (EnrollmentReportingModel)Context.DbContext;
var results = (from ecew in db.A
join ecewe in db.B on ecew.ID
equals ecewe.ExchangeChangeEnrollmentWindowID into temp
from j in temp.DefaultIfEmpty()
join cecr in db.C on ecew.ConsumerExchangeChangeRequestID equals cecr.ID
join con in db.D on cecr.ConsumerID equals con.ID
where consumerIDs.Contains(con.ID) && !ecew.Deleted
select new E
{
ConsumerID = con.ID,
OrganizationID = con.OrganizationID,
StartDate = ecew.StartDate,
EndDate = ecew.EndDate,
Deleted = ecew.Deleted
}).ToList();
return results;
}
Here is the dto class
public class E : ILzDto
{
public int ConsumerID { get; set; }
public int OrganizationID { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public bool Deleted { get; set; }
}

I think you want Any, not contains:
public ICollection<ConsumerExchangeChangeDto> GetByConsumers(List<int> consumerIDs)
{
EnrollmentReportingModel db = (EnrollmentReportingModel)Context.DbContext;
var results = (from ecew in db.A
join ecewe in db.B on ecew.ID
equals ecewe.ExchangeChangeEnrollmentWindowID into temp
from j in temp.DefaultIfEmpty()
join cecr in db.C on ecew.ConsumerExchangeChangeRequestID equals cecr.ID
where consumerIDs.Any(x => x == cecr.ConsumerID) && !ecew.Deleted
select new E
{
ConsumerID = cecr.ConsumerID,
OrganizationID = con.OrganizationID,
StartDate = ecew.StartDate,
EndDate = ecew.EndDate,
Deleted = false
}).ToList();
return results;
}

Related

how to use in clause in Linq Query and pass it dynamically from code

I am converting my project to EF Core in my old project I have a query running.
IDictionary<int, IGrouping<int, UserPurchaseItemAddonWithAmount>> addons =
context.Fetch<UserPurchaseItemAddonWithAmount>($"Select UPIA.*, EA.Amount From UserPurchaseItemAddons UPIA Inner Join ExtraAddons EA on UPIA.AddonID = EA.AddonID Where UPIA.UserPurchaseItemID in ({string.Join(',', userPurchaseItems.Select(S => S.UserPurchaseItemID))})")
.GroupBy(G => G.UserPurchaseItemID).ToDictionary(D => D.Key);
I need to convert this query in to Linq query what I am doing is below
IDictionary<int, IGrouping<int, UserPurchaseItemAddonWithAmount>> addons =
(from f in context.UserPurchaseItemAddons
join s in context.ExtraAddons
on f.AddonId equals s.AddonId
select new
{
Amount = s.Amount,
UserPurchaseItemAddonID = f.UserPurchaseItemAddonId,
UserPurchaseItemID = f.UserPurchaseItemId,
BranchItemVariantID = f.BranchItemVariantId,
AddonID = f.AddonId,
UserID = f.UserId,
IsDeleted = f.IsDeleted,
ModifiedOn = f.ModifiedOn,
ModifiedBy = f.ModifiedBy,
Reason = f.Reason,
}).GroupBy(G => G.UserPurchaseItemID).ToDictionary(D => D.Key);
This query is causing a compiler error related to casting to IGrouping<int, UserPurchaseItemAddonWithAmount> to an anonymous type. The other thing is that how can I apply in clause in where condition in above query, just like the first query .
class
public class UserPurchaseItemAddonWithAmount
{
public decimal Amount { get; set; }
public int UserPurchaseItemAddonID { get; set; }
public int UserPurchaseItemID { get; set; }
public int BranchItemVariantID { get; set; }
public int AddonID { get; set; }
public int UserID { get; set; }
public bool IsDeleted { get; set; }
public DateTime? ModifiedOn { get; set; }
public int? ModifiedBy { get; set; }
public string? Reason { get; set; }
}
Try the following query. Main mistake that you have returned anonymous class.
var purchaseItemIds = userPurchaseItems.Select(S => S.UserPurchaseItemID);
IDictionary<int, IGrouping<int, UserPurchaseItemAddonWithAmount>> addons =
(from f in context.UserPurchaseItemAddons
join s in context.ExtraAddons on f.AddonId equals s.AddonId
where purchaseItemIds.Contains(f.UserPurchaseItemID)
select new UserPurchaseItemAddonWithAmount
{
Amount = s.Amount,
UserPurchaseItemAddonID = f.UserPurchaseItemAddonId,
UserPurchaseItemID = f.UserPurchaseItemId,
BranchItemVariantID = f.BranchItemVariantId,
AddonID = f.AddonId,
UserID = f.UserId,
IsDeleted = f.IsDeleted,
ModifiedOn = f.ModifiedOn,
ModifiedBy = f.ModifiedBy,
Reason = f.Reason,
})
.AsEnumerable()
.GroupBy(G => G.UserPurchaseItemID)
.ToDictionary(D => D.Key);

How to export data on excel using linq?

I have a problem, my data does populate but the challenge is now, data is not corresponding to my record list. E.g if i do a query for Year, Week 2020, 53 both front end this has no record and so does on my query on the database. On my MVC application i get duplicate record for year, week and day. Let me share my logic with you all. My linq sql does not check if there are no record either and im stuck, please help mates.
SQL tables for both tables here
SELECT TOP (1000) [WeekId]
,[WeekNum]
,[Year]
,[CreatedDate]
,[CreatedBy]
,[ModifiedDate]
,[ModifiedBy]
,[InActive]
FROM [ProductionManagement].[Schedule].[Week]
SELECT TOP (1000) [ProductionDayId]
,[WeekId]
,[ProductionDate]
,[DayOfWeek]
,[CreatedDate]
,[CreatedBy]
,[ModifiedDate]
,[ModifiedBy]
,[InActive]
FROM [ProductionManagement].[Schedule].[ProductionDay]
Order by ProductionDate
This is my model class
public class ExtractionViewModel
{
public string Year { get; set; }
public int Week { get; set; }
[DataType(DataType.Date)]
public DateTime Day { get; set; }
// public string VW240 { get; set; }
public string VW250 { get; set; }
public string VW270 { get; set; }
public string VW2502PA { get; set; }
public string VW270PA { get; set; }
}
And this is the method that loads it
public IList<ExtractionViewModel> GetExtractionViewModels()
{
int Count;
var db = new ProductionManagementEntities();
var scheduleList = (from p in db.ProductionDays
from m in db.Models
from mx in db.Models
from mt in db.Models
from mv in db.Models
from wk in db.Models
join w in db.Weeks on p.WeekId equals w.WeekId
orderby w.Year descending , m.Name descending, p.ProductionDate descending, w.WeekNum descending, mt.Name descending, mx.Name descending, mv.Name descending
My problem is on this method exactly there is so much duplicate when i download my excel and compare with query on the database they not complementing and need some here to these records.
where (mx.InActive == true)
where (mt.InActive == false)
where(m.InActive == false)
where(mv.InActive == false)
where (mt.Name == "VW270")
where(mx.Name == "VW250")
where(m.Name == "VW270PA")
where(mv.Name == "VW250/2PA")
select new ExtractionViewModel
{
Year = w.Year,
Day = p.ProductionDate,
Week = w.WeekNum,
VW270 = mt.Name,
VW270PA = m.Name,
VW250 = mx.Name,
VW2502PA = mv.Name,
}).ToList();
return scheduleList;
}
The code that generates the Excel file is
public void ExportToExcel()
{
var v = new GridView();
v.DataSource = this.GetExtractionViewModels();
v.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=ExtractionRecords.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter objStringWriter = new StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(objStringWriter);
v.RenderControl(htmlTextWriter);
Response.Output.Write(objStringWriter.ToString());
Response.Flush();
Response.End();
//return View("DataResult");
}
public ActionResult DataResult()
{
return View(this.GetExtractionViewModels());
}
// Front end images

Linq query for joining many to many tables

I'm new at LINQ and need your advice.
I have 2 tables like these:
public class Subjects
{
public Subjects()
{
Classes = new List<Classes>();
}
public int Id { get; set; }
public string SubjectName { get; set; }
public virtual List<Classes> Classes { get; set; }
}
public class Classes
{
public Classes()
{
Subjects = new List<Subjects>();
}
public int Id { get; set; }
public string ClassName { get; set; }
public virtual List<Subjects> Subjects { get; set; }
}
And Entity Framework create SubjectClasses
public SubjectsMap()
{
this.HasKey(s => s.Id);
this.Property(s => s.SubjectName)
.IsRequired()
.HasMaxLength(50);
this.ToTable("Subjects");
this.HasMany(c => c.Classes)
.WithMany(s => s.Subjects)
.Map(cs =>
{
cs.MapLeftKey("SubjectId");
cs.MapRightKey("ClassId");
cs.ToTable("SubjectClasses");
});
}
Subject---- SubjectClasses ----- Classes
My Context doesn't have SubjectClasses, so I need to convert the SQL query to Linq or Lambda. But Linqpad doesn't help me or I can't use it. I simply want to take Firstname, SubjectName
SELECT st.Firstname, s.SubjectName
FROM SubjectClasses sc
INNER JOIN Subjects s on s.Id = sc.SubjectId
INNER JOIN Students st on st.ClassId = sc.ClassId
WHERE sc.ClassId = 3
It's working.
(from st in context.Students
from s in context.Subjects
join c in context.Classes
on new { stuId = st.ClassId } equals new { stuId = c.Id }
select new ComplexExamResult
{
Id = c.Id,
Firstname = st.Firstname,
SubjectName = s.SubjectName
}).Where(c => c.Id == classId).AsNoTracking().ToList();

linq query with a list in the where clause

I have a linq query written in the below format. Now when I am passing a consumerID it works fine and I am able to put it in the where clause. However when I try to pass a list of consumerIds, how can I put this in the where clause. I have looked through some solution online and they all use some other linq format which I dont want to use.
Please suggesest if I can have a list in the where clause, something similar to how we can have in clause in sql??
public ICollection<ConsumerExchangeChangeDto> GetByConsumers(List<int> consumerIDs)
{
EnrollmentReportingModel db = (EnrollmentReportingModel)Context.DbContext;
var results = (from ecew in db.A
join ecewe in db.B on ecew.ID
equals ecewe.ExchangeChangeEnrollmentWindowID into temp
from j in temp.DefaultIfEmpty()
join cecr in db.C on ecew.ConsumerExchangeChangeRequestID equals cecr.ID
join con in db.D on cecr.ConsumerID equals con.ID
where con.ID.Contains(consumerIDs) && !ecew.Deleted
select new E
{
ConsumerID = con.ID,
OrganizationID = con.OrganizationID,
StartDate = ecew.StartDate,
EndDate = ecew.EndDate,
Deleted = ecew.Deleted
}).ToList();
return results;
}
Here is the dto class
public class E : ILzDto
{
public int ConsumerID { get; set; }
public int OrganizationID { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public bool Deleted { get; set; }
}
Change this:
where con.ID.Contains(consumerIDs)
to this:
where consumerIDs.Contains(con.ID)
This will check if the id of the items in the select statement are in the input list.

Raven Db Querying

I am using Map Reduce index for query. And I want to select filter by licenceId/licenceIds which may be one or many separated by comma entered in text box
e.g.
L1 (select having LicenseId only L1)
L1,L2 (select having LicenseId only L1 OR L2)
L2,L3,L5 (select having LicenseId only L3 OR L3 OR L5)
Here is result document:
public class GrossSalesByRevenueClass
{
public string LicenseId { get; set; }
public string RevClass { get; set; }
public decimal GrossSales { get; set; }
public decimal NetSales { get; set; }
public int Quantity { get; set; }
public bool NonSales { get; set; }
public DateTime Day { get; set; }
public string DayName { get; set; }
public int Month { get; set; }
public int Quarter { get; set; }
public int Year { get; set; }
}
Index is:
public class IdxGrossSalesByRevenueClassByDay : AbstractIndexCreationTask<Ticket, GrossSalesByRevenueClass>
{
public IdxGrossSalesByRevenueClassByDay()
{
Map = docs => from doc in docs
from c in doc.Coversfrom t in c.TicketItems
select new
{
LicenseId = doc.LicenseId,
RevClass = t.RevenueClass,
GrossSales = t.TicketItemGross,
NetSales = t.NetPrice,
Quantity = t.Quantity,
NonSales = t.IsNonSales,
Day = doc.TicketDate.Date,
DayName = doc.TicketDate.ToString("ddd")
};
Reduce = result => from r in result
group r by new { r.NonSales, r.RevClass, r.Day, r.LicenseId } into g
select new
{
LicenseId = g.Key.LicenseId,
RevClass = g.Key.RevClass,
GrossSales = g.Sum(x => x.GrossSales),
NetSales = g.Sum(x => x.NetSales),
Quantity = g.Sum(x => x.Quantity),
NonSales = g.Key.NonSales,
Day = g.Key.Day,
DayName = g.Select(x => x.DayName).FirstOrDefault(),
};
}
}
And I am querying like following:
GrossSalesByRevenueClassCollection = session.Query<GrossSalesByRevenueClass, IdxGrossSalesByRevenueClassByDay>()
.TransformWith<GrossSalesByRevenueClassTransformer, GrossSalesByRevenueClass>()
.Where(x => x.Day >= d1 && x.Day <= d2 && (?????))
In place of (?????) there should be License id list (L1 OR L2)
I tried Contains() in where but not working for me please tell me how do I query an index
for such a requirement.
something like this
var licenses = userLicenses.Split(",");
GrossSalesByRevenueClassCollection = session.Query<GrossSalesByRevenueClass, IdxGrossSalesByRevenueClassByDay>()
.Where(x => x.Day >= d1 && x.Day <= d2 && x.LicenseId.In(licenses))