EF Lambda How to make projection for GroupJoin - entity-framework

I am trying to query EF models. (GameBank and GameCouponBank) How can I make a projection for left outer join (GoupJoin)?
Can I make projection for Coupons?
Here is my query
var gameBankResult = context.GameBanks.GroupJoin(context.GameCouponBanks, g => g.GameBankID, gc => gc.GameBankID,
(g,gc) => new {
g.quantity,
g.currency,
g.initiationResultCode,
g.productCode,
g.productDescription,
g.referenceId,
g.responseDateTime,
g.unitPrice,
g.totalPrice,
Coupons = gc
})
.Where(g => g.productCode == initiate.productCode)
.Select(s => s);
Here is models:
public class GameBank
{
public int GameBankID { get; set; }
public string referenceId { get; set; }
public string productCode { get; set; }
public int quantity { get; set; }
public string version { get; set; }
public DateTime? requestDateTime { get; set; } = DateTime.Now;
public int? customerID { get; set; }
public string password { get; set; }
public DateTime? responseDateTime { get; set; } = DateTime.Now;
public string initiationResultCode { get; set; }
public string companyToken { get; set; }
public int used { get; set; }
public string productDescription { get; set; }
public string currency { get; set; }
public double unitPrice { get; set; }
public double totalPrice { get; set; }
public virtual List<GameCouponBank> coupons { get; set; }
}
public class GameCouponBank
{
public int Id { get; set; }
public int GameBankID { get; set; }
public DateTime? expiryDate { get; set; }
public string Serial { get; set; }
public string Pin { get; set; }
}

You don't need to use GroupJoin explicitly. You can simply project your query as follows:
var gameBankResult = context.GameBanks.Where(g => g.productCode == initiate.productCode)
.Select(g => new {
g.quantity,
g.currency,
g.initiationResultCode,
g.productCode,
g.productDescription,
g.referenceId,
g.responseDateTime,
g.unitPrice,
g.totalPrice,
Coupons = g.coupons.Select(c => new {c.Id, c.GameBankID,...}).ToList() //<-- Here is the projection for coupons
}).FirstOrDefault(); // I assume you are returning single entity, if not then use `.ToList()` instead of `.FirstOrDefault()`

Related

Can anyone give me a solution how we will merge the two different repositories i.e.. two tables in a same database we want to use a Linq query

Working code - but it is not getting output what is the wrong in this code:
var result = _favouriteProjectRepository.Entity()
.Where(x => x.UserId == userId)
.Select(x => new FavouriteProject
{
ProjectId = x.ProjectId,
}).ToList();
var resultset = await _projectrepository.Entity()
.Where(x => (filters.FiscalYear == null ||
filters.FiscalYear.Contains(Convert.ToInt32(x.ContractNo.ToString().Substring(0, 2)))) &&
(filters.IsFavourite == false &&
result.Contains(x.Id).ToString()))
.Select(x => new Tests
{
Id = x.Id,
Name = x.Name,
AdvertisementStatusId = x.AdvertisementStatusId,
CreatedOn = x.CreatedOn,
ContractNo = x.ContractN0,
})
.OrderBy(x => x.Name)
.ToListAsync();
Models:-
public class FavouriteProject
{
public int ProjectId { get; set; }
public string UserId { get; set; }
public virtual Project Project { get; set; }
}
public class Tests
{
public int Id { get; set; }
public string Name { get; set; }
public int? ContractNo { get; set; }
public int? AdvertisementStatusId { get; set; }
public DateTime? CreatedOn { get; set; }
public virtual ICollection<FavouriteCompany> FavouriteCompany { get; set; }
}
**filters**
public class ProjectFilters
{
public List<int> FiscalYear { get; set; }
public bool IsFavourite { get; set; }
}
**Project Model**
public class Project
{
public int Id { get; set; }
public string ProcurmentNo { get; set; }
public int? ContractNo { get; set; }
public int? ProjectSizeId { get; set; }
public int? SelectionProcedureId { get; set; }
public int? ResponseRequestedId { get; set; }
public int? AdvertisementStatusId { get; set; }
public int? NoOfPages { get; set; }
public string PreQualificationRequirements { get; set; }
public string Description { get; set; }
public string Name { get; set; }
public string MultilineDescription { get; set; }
public string BridgDesignWorkType { get; set; }
public string DbeMbeRequirements { get; set; }
public string SpecialNote { get; set; }
public decimal? BudgetAmount { get; set; }
public decimal? EstimatedContractAmount { get; set; }
public decimal? MaxumumContractAmount { get; set; }
public bool? IsMultipleContracts { get; set; }
public string ProposedScopeLoc { get; set; }
public string BondingRequirements { get; set; }
public string TechQuestionsAddressedTo { get; set; }
public int Status { get; set; }
public int? DistrictId { get; set; }
public DateTime? CreatedOn { get; set; }
public string ResponseEmail { get; set; }
public string ViewRFP { get; set; }
public string AdditionalInformation { get; set; }
public string LowBidDesign { get; set; }
public string AdminNote { get; set; }
public string MeetingLocationNotes { get; set; }
public string FdotKey { get; set; }
//public DateTime? EventDate { get; set; }
public bool IsUpdatesLocked { get; set; }
public bool? BdiProjectIndicator { get; set; }
public string LiabilityInsurance { get; set; }
public string ProjectThreshold { get; set; }
public int NumberOfContracts { get; set; }
public int? RelatedProjectCount { get; set; }
public string AdvertisementSpecialNotes { get; set; }
public string FMNSpecialNotes { get; set; }
public virtual ProjectSize ProjectSize { get; set; }
public virtual SelectionProcedure SelectionProcedure { get; set; }
public virtual ResponseRequested ResponseRequested { get; set; }
public virtual AdvertisementStatus AdvertisementStatus { get; set; }
public virtual District District { get; set; }
public virtual ICollection<ProjectEvent> ProjectEvents { get; set; }
public virtual ICollection<FinancialManagementNumber> FinancialManagementNumbers { get; set; }
public virtual ICollection<ProjectWorkGroup> ProjectWorkGroups { get; set; }
public virtual ICollection<ScrapedLink> ScrapedLinks { get; set; }
public virtual ICollection<ProjectStandardNote> ProjectStandardNotes { get; set; }
public virtual ICollection<FtpFileProject> FtpFileProjects { get; set; }
public virtual ICollection<CompanyProject> CompanyProjects { get; set; }
public virtual ICollection<ContactProject> ContactProjects { get; set; }
public virtual ICollection<ProjectUnderUtilizedWorkGroup> ProjectUnderUtilizedWorkGroups { get; set; }
public virtual ICollection<WorkProgram> WorkPrograms { get; set; }
[NotMapped]
public virtual ICollection<ScrapedProjectModel> ScrapedProjects { get; set; }
// public virtual FavouriteProject FavouriteProject { get; set; }
Can anyone give me simplified query to call both in single request?
And I have added my models and filters you can go through it I have used only one filters and the model of project because in that class only I have mentioned
Try the following query:
var query = _projectrepository.Entity().AsQueryable();
if (filters.FiscalYear?.Count > 0)
{
query = query.Where(x => filters.FiscalYear.Contains(Convert.ToInt32(x.ContractNo.ToString().Substring(0, 2))));
}
if (filters.IsFavourite)
{
var favouriteProjects = _favouriteProjectRepository.Entity()
.Where(x => x.UserId == userId);
query =
from p in query
join f in favouriteProjects on p.Id equals f.ProjectId
select p;
}
var resultset = await query
.Select(x => new Tests
{
Id = x.Id,
Name = x.Name,
AdvertisementStatusId = x.AdvertisementStatusId,
CreatedOn = x.CreatedOn,
ContractNo = x.ContractN0,
})
.OrderBy(x => x.Name)
.ToListAsync();

Entity-framework The column name is specified more than once in the SET clause or column list of an INSERT

I have entity
public class ImageTeam
{
public int Id { get; set; }
public int TeamID { get; set; }
public Team Team { get; set; }
public int PostTeamID { get; set; }
public string Image { get; set; }
public int ImageType { get; set; }
public int StatusPublic { get; set; }
public int StatusActive { get; set; }
public DateTime CreatedAt { get; set; }
}
public class Team
{
public int Id { get; set; }
public string Name { get; set; }
public int NoMember { get; set; }
public float Score { get; set; }
public int StatusActive { get; set; }
public int TeamType { get; set; }
public virtual List<TeamGroup> ListMember { get; set; }
public virtual List<ImageTeam> ListAvatar { get; set; }
public virtual List<ImageTeam> ListBanner { get; set; }
public DateTime CreatedAt { get; set; }
}
config data context
modelBuilder.Entity<Team>(entity =>
{
entity.HasMany(x => x.ListAvatar)
.WithOne(t => t.Team)
.HasForeignKey(pv => pv.TeamID);
});
when I post the data insert a new record entity ImageTeam then it show exception
I need to do...Help me
In the Team class you add another relation ListBanner to ImageTeam class ,you have not set an foreign key for it, so EF automatically creates a TeamID and because TeamId already in the class, it's throw exception . You also need to set an foreign key for second relation.
public class ImageTeam
{
public int Id { get; set; }
public int TeamID { get; set; }
public Team Team { get; set; }
public int BannerTeamId { get; set; }
public Team BannerTeam { get; set; }
public int PostTeamID { get; set; }
public string Image { get; set; }
public int ImageType { get; set; }
public int StatusPublic { get; set; }
public int StatusActive { get; set; }
public DateTime CreatedAt { get; set; }
}
entity.HasMany(x => x.ListAvatar)
.WithOne(t => t.Team)
.HasForeignKey(pv => pv.TeamID).OnDelete(DeleteBehavior.Restrict);
entity.HasMany(x => x.ListBanner)
.WithOne(t => t.BannerTeam)
.HasForeignKey(pv => pv.BannerTeamId).OnDelete(DeleteBehavior.Restrict);
I have found a solution:
edit Team entity:
public class Team
{
public int Id { get; set; }
public string Name { get; set; }
public int NoMember { get; set; }
public float Score { get; set; }
public int StatusActive { get; set; }
public int TeamType { get; set; }
public virtual List<TeamGroup> ListMember { get; set; }
public virtual List<ImageTeam> ListImage { get; set; }
public DateTime CreatedAt { get; set; }
}
*no config data context
create new model: TeamViewModel
public class TeamViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public int NoMember { get; set; }
public float Score { get; set; }
public int StatusActive { get; set; }
public int TeamType { get; set; }
public virtual List<TeamGroupViewModel> ListMember { get; set; }
public virtual List<ImageTeam> ListImage { get; set; }
public string AvatarUrl { get; set; }
public virtual List<ImageTeam> ListAvatar { get; set; }
public string BannerUrl { get; set; }
public virtual List<ImageTeam> ListBanner { get; set; }
public virtual List<ImageTeam> ListPost { get; set; }
}
in controller :
[Route("api/[controller]/{id}/view")]
[HttpGet("{id}")]
public IActionResult GetById(int id)
{
var team = _teamService.GetById(id);
var model = _mapper.Map<TeamViewModel>(team);
model = parserImageTeam(model);
return Ok(model);
}
[Route("api/[controller]/{UserId}/view-teams")]
[HttpGet("{UserId}")]
public IActionResult GetAllTeamOfUser(int UserId)
{
// list teams
var teams = _teamService.GetTeamOfUser(UserId);
var _teams = _mapper.Map<IList<TeamViewModel>>(teams);
var newTeams = new List<TeamViewModel>();
foreach (TeamViewModel team in _teams)
{
newTeams.Add(parserImageTeam(team));
}
return Ok(newTeams);
}
private TeamViewModel parserImageTeam(TeamViewModel teamModel)
{
var imageAvatars = new List<ImageTeam>();
var imageBanners = new List<ImageTeam>();
var imagePosts = new List<ImageTeam>();
bool avt = false, banner = false;
foreach (ImageTeam image in teamModel.ListImage)
{
if (image.ImageType == Constants.ImageType.IMAGE_AVATAR_TEAM)
{
image.Image = parserUrlImage(image);
imageAvatars.Add(image);
if (!avt)
{
teamModel.AvatarUrl = image.Image;
avt = true;
}
}
if (image.ImageType == Constants.ImageType.IMAGE_BANNER_TEAM)
{
image.Image = parserUrlImage(image);
imageBanners.Add(image);
if (!banner)
{
teamModel.BannerUrl = image.Image;
banner = true;
}
}
if (image.ImageType == Constants.ImageType.IMAGE_POST_TEAM)
{
image.Image = parserUrlImage(image);
imagePosts.Add(image);
banner = true;
}
}
teamModel.ListAvatar = imageAvatars;
teamModel.ListBanner = imageBanners;
teamModel.ListPost = imagePosts;
return teamModel;
}
private string parserUrlImage(ImageTeam model)
{
string url = Configuration.GetValue<string>("BaseVariables:BaseUrl");
// another controller handle request (ImagesController)
return model.Image = url + "/Images/" + Constants.ImageType.getFolderName(model.ImageType).ToLower() + "/" + model.TeamID + "?ImageType=" + model.ImageType + "&imageName=" + model.Image;
}

EF-Core query but value missing, even it show in database

here is the simple query code...
var order = await _context.ProductOrders
.FirstOrDefaultAsync(x => x.Id == orderId.ToInt());
This is the entity of ProdictOrders
public class ProductOrder
{
public int Id { get; set; }
public int MovieTicketEnrollmentId { get; set; }
public string ProductOrderStatusCode { get; set; }
public int? InvoiceId { get; set; }
public DateTime CreateDate { get; set; }
public string CreateBy { get; set; }
public DateTime? UpdateDate { get; set; }
public string UpdateBy { get; set; }
/**
* Navigation Property
*/
public MovieTicketEnrollment MovieTicketEnrollment { get; set; }
public ProductOrderStatus ProductOrderStatus { get; set; }
public ICollection<ProductOrderItem> ProductOrderItems { get; set; }
public Invoice Invoice { get; set; }
}
This data in the database
And what I got after executing query command above... what's just happening here?
MovieTicketEnrollmentId should equal to 1

Complex subquery in Entity Framework 6

I have an entity called Insurance like this:
public class Insurance : BaseEntity, IExpirationDocument
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public override int Id { get; set; }
[Column(TypeName = "NVARCHAR")]
[StringLength(256)]
public string PathToCertificate { get; set; }
[Column(TypeName = "NVARCHAR")]
[StringLength(50)]
public string Filename { get; set; }
public int Value { get; set; }
public string Name => InsuranceType.Name;
public DateTime ExpiryDate { get; set; }
public DateTime IssueDate { get; set; }
public bool Active { get; set; }
public int InsuranceTypeId { get; set; }
public virtual InsuranceType InsuranceType { get; set; }
public int InsurerId { get; set; }
public virtual Insurer Insurer { get; set; }
public int ApplicantId { get; set; }
public virtual Applicant Applicant { get; set; }
public int? DocumentEmailHistoryId { get; set; }
public virtual DocumentEmailHistory DocumentEmailHistory { get; set; }
public Insurance()
{
Active = true;
}
}
Would it be possible to do this type of query with Entity Framework:
SELECT *
FROM Insurances i1
INNER JOIN
(SELECT
insuranceTypeId, applicantid, MAX(IssueDate) as 'maxissuedate'
FROM
Insurances
GROUP BY
insuranceTypeId, applicantid) AS i2 ON i1.applicantid = i2.applicantid
AND i1.insuranceTypeId = i2.insuranceTypeId
WHERE
i1.issueDate = i2.maxissuedate
If you are trying to get latest issued Insurance according to InsuranceTypeId and ApplicantId you can group data according to needed properties, order by IssueDate descendingly and take only one Insurance info. Of course it will not give you the same query but it will give you the same result:
var result = context.Insurances
.GroupBy(m => new { m.InsuranceTypeId , m.ApplicantId })
.Select( g => new
{
MaxInsurance = g.OrderByDescending(m => m.IssueDate)
.Take(1)
})
.SelectMany(m => m.MaxInsurance);

Entity Framework Linq Entity convert to CustomModel

I have the following linq to entity:
var dbShifts = DbContext.Set < SetupShift > ()
.AsNoTracking()
.Where(s => s.ShiftCode == shiftCode).ToList();
The Entity SetupShift has the following properties:
public class SetupShift
{
public int ShiftId { get; set; }
public string ShiftCode { get; set; }
public byte Day { get; set; }
public TimeSpan InTime { get; set; }
public TimeSpan OutTime { get; set; }
public int WorkHours { get; set; }
public TimeSpan LunchOut { get; set; }
public TimeSpan LunchIn { get; set; }
public bool IsActive { get; set; }
public string CategoryType { get; set; }
}
Now, I need to wrap it to a custom model ShiftModel:
public class ShiftModel
{
public int ShiftId { get; set; }
public string ShiftCode { get; set; }
public byte Day { get; set; }
public string DayName { get; set; }
public string InTime { get; set; }
public string OutTime { get; set; }
public int WorkHours { get; set; }
public string LunchOut { get; set; }
public string LunchIn { get; set; }
public bool IsActive { get; set; }
public string CategoryType { get; set; }
}
The only difference between the EF Entity model and my ShiftModel is that the TimeSpan properties are String in the Custom model.
I would like to know if there is a fast way to generate my ShiftModel from my Entity data instead of looping every entity:
List<ShiftModel> shifts = new List<ShiftModel>();
foreach(var entity in SetupShift){
....
newShiftModel = new ShiftModel();
newShiftModel.InTime = new TimeSpan(0, 0, 0).ToString(#"hh\:mm");
....
....
shifts.Add(newShiftModel);
}
You could do something like
var dbShifts = DbContext.Set < SetupShift > () .AsNoTracking() .Where(s => s.ShiftCode == shiftCode).Select(x => new ShiftModel() {
ShiftId = x.ShiftId,
ShiftCode = x.ShiftCode,
Etc.....
}).ToList();
Apologies for the poor formatting answering this from my phone.