join two different list by id into one list - c#

I've got two different list of two different objects. Then i got one list of a viewmodel that contains properties from both the objects and i want them to be joined into that list.
//Product
public string id { get; set; }
public string unitMeasurement { get; set; }
public Nullable<int> minOrderQty { get; set; }
public Nullable<int> packSize { get; set; }
public string leadTime { get; set; }
public Nullable<int> generalAccessoryCategoryId { get; set; }
public string Company { get; set; }
public Nullable<decimal> Weight { get; set; }
public Nullable<int> ProductType { get; set; }
//ProductDescription
public string id { get; set; }
public string language { get; set; }
public string shortDescription { get; set; }
public string detailDescription { get; set; }
public string Name { get; set; }
public Nullable<int> Rank { get; set; }
public Nullable<System.DateTime> StartDate { get; set; }
public Nullable<System.DateTime> EndDate { get; set; }
public class ProductResponse
{
public string id { get; set; }
//Product
public string unitMeasurement { get; set; }
public Nullable<int> minOrderQty { get; set; }
public Nullable<int> packSize { get; set; }
public string leadTime { get; set; }
public Nullable<int> generalAccessoryCategoryId { get; set; }
public string Company { get; set; }
public Nullable<decimal> Weight { get; set; }
public Nullable<int> ProductType { get; set; }
//ProductDescription
public string language { get; set; }
public string shortDescription { get; set; }
public string detailDescription { get; set; }
public string Name { get; set; }
public Nullable<int> Rank { get; set; }
public Nullable<System.DateTime> StartDate { get; set; }
public Nullable<System.DateTime> EndDate { get; set; }
}
So i just want to join a list of products and a list of productdescriptions into a list of productResponse. How can i do this? id of product and productdescription is the same so thats what i want to join them on.

Join them on id and then call ToList:
var productResponses = from p in products
join pd in productDescriptions
on p.id equals pd.id
select new ProductResponse
{
id = p.id,
language = pd.language,
// ...
}
var list = productResponses.ToList();

Related

Null value in query using Select statement

I want to create a query that will return an AgencyContractData object containing a DocumentDto object, but it may be that the original object does not contain a foreign key on the Document. I can't use ternary operator in an Entity-Framwork LINQ query. How it is possible to implement it (Required that select be converted to sql query)?
var contractList = await query
.Select(contract => new AgencyContractData
{
ContractId = contract.Id,
ContractNumber = contract.ContractNumber,
CustomerId = contract.CustomerId,
CustomerName = contract.CustomerName,
Group = contract.Group,
CommodityType = contract.CommodityType,
SupplierName = contract.SupplierName,
StartDate = contract.StartDate,
EndDate = contract.EndDate,
ExecutionDate = contract.ExecutionDate,
ContractUnit = contract.ContractUnit,
Comment = contract.Comment,
Pricing = contract.Pricing,
SecondaryCustomerName = contract.SecondaryCustomerName,
ContractType = contract.ContractType,
AnnualVolume = contract.AnnualVolume,
Document = new DocumentDto
{
DocumentId = contract.Document.Id,
CounterPartyId = contract.Document.CounterPartyId,
FilePath = contract.Document.FilePath,
DocumentTitle = contract.Document.DocumentTitle,
IsCustomerUpload = contract.Document.IsCustomerUpload,
DocumentBytes = null
},
DocumentName = contract.DocumentName,
ContractNumberInt = contract.ContractNumberInt,
ContractNumberString = contract.ContractNumberString,
MsaBaseNumber = contract.MsaBaseNumber,
NotificationDays = contract.NotificationInDays,
State = contract.State,
CreatedOn = contract.CreatedOn,
CreatedBy = contract.CreatedBy,
ModifiedOn = contract.ModifiedOn,
ModifiedBy = contract.ModifiedBy,
It is the AgencyContract entity:
public class Contract : IEntity<long>
{
public long Id { get; set; }
public string ContractNumber { get; set; }
public long? ContractUnitId { get; set; }
public int? NumPricePeriods { get; set; }
public double? Tolerance { get; set; }
public ContractTypeEnum? ContractType { get; set; }
public ContractTolerancePeriodEnum? ContractTolerancePeriod { get; set; }
public bool IsRelyContract { get; set; }
public int TermsEndNoticeDays { get; set; }
public bool IsProrated { get; set; }
public bool IsContinuation { get; set; }
public long SupplierId { get; set; }
public long? DocumentId { get; set; }
public long? BrokerId { get; set; }
public BillTypeEnum? BillType { get; set; }
public string ExternalId { get; set; }
#region Navigation Properties
public virtual Supplier Supplier { get; set; }
public virtual Broker Broker { get; set; }
public virtual ContractUnit ContractUnit { get; set; }
public virtual Account Account { get; set; }
public virtual List<UsnAccountToContract> UsnAccountToContracts { get; set; }
public virtual List<ProviderLookup> ProviderLookups { get; set; }
public virtual List<ContractNotification> ContractNotifications { get; set; }
public virtual List<ContractVolume> ContractVolumes { get; set; }
public virtual Document Document { get; set; }
#endregion
And I want to make a AgencyContractData object using Select:
public class AgencyContractData
{
public int? AnnualVolume { get; set; }
public string Comment { get; set; }
public AgencyCommodityTypeEnum CommodityType { get; set; }
public long ContractId { get; set; }
public string ContractNumber { get; set; }
public long? ContractNumberInt { get; set; }
public string ContractNumberString { get; set; }
public int? ContractReportLevelByGlobalSearch { get; set; }
public AgencyContractTypeEnum ContractType { get; set; }
public AgencyContractUnitEnum ContractUnit { get; set; }
public Guid? CreatedBy { get; set; }
public DateTime? CreatedOn { get; set; }
public long? CustomerId { get; set; }
public string CustomerName { get; set; }
public string DocumentName { get; set; }
public DocumentDto Document { get; set; }
public DateTime? EndDate { get; set; }
public DateTime ExecutionDate { get; set; }
public string Group { get; set; }
public List<AgencyLocationData> Locations { get; set; }
public Guid? LockedBy { get; set; }
public DateTime? LockedOn { get; set; }
public string Md5Hash { get; set; }
public Guid? ModifiedBy { get; set; }
public DateTime? ModifiedOn { get; set; }
public string MsaBaseNumber { get; set; }
public int? NotificationDays { get; set; }
public DateTime? NotificationSentOn { get; set; }
public string Pricing { get; set; }
public string SecondaryCustomerName { get; set; }
public int Sites { get; set; }
public DateTime StartDate { get; set; }
public string State { get; set; }
public string Status { get; set; }
public string SupplierName { get; set; }

EF CORE understanding relationships in a Gym setting

Ok I am kinda stuck I need a ef query that will get me the following data.
I have sessions which are created at the Gym I am using ef core here so
In the main grid I need to list the students that our their for the workout that day.
ID
Session Name
Start Date
TeamId
1
Test 1
06/11/2021
1
---
2
Test 2
05/11/2021
2
---
I have table Students which has a team Id
ID
FirstName
Last Name
TeamId
1
Matt
Smith
1
---
2
Martha
Jones
2
---
Team Includes the students and is linked back to the Student via Team Id
ID
Name
Session Id
1
Test Team
1
!2
Test Team 2
2
For Example what I want to be able to do is Pick the session that is on the start date of the 5 and display only the students attending that day.
My Poco Class for Session
public class Session
{
public int Id { get; set; }
public string? Name { get; set; }
public int OccuranceType { get; set; }
public int? StaffId { get; set; }
public int? Day { get; set; }
public int? Duration { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public int? Status { get; set; }
public int? TeamId { get; set; }
public Team? Team { get; set; }
public bool? IsDeleted { get; set; }
public bool? IsActive { get; set; }
public string? CreatedBy { get; set; }
public string? LastModifiedBy { get; set; }
public DateTime? LastUpdatedDate { get; set; }
public DateTime? CreatedDate { get; set; }
}
Student
public class Student
{
public int Id { get; set; }
public int? Type { get; set; }
public int? CoachId { get; set; }
public virtual Coach Coach { get; set; }
public int? TeamId { get; set; }
public virtual Team Team { get; set; }
public string? FirstName { get; set; }
public string? Surname { get; set; }
public DateTime? DOB { get; set; }
public decimal? Weight { get; set; }
public decimal? Height { get; set; }
public int? Gender { get; set; }
public string? Photo { get; set; }
public int? Age { get; set; }
public string? AddressLine1 { get; set; }
public string? AddressLine2 { get; set; }
public string? State { get; set; }
public string? ZipCode { get; set; }
public string? Mobile { get; set; }
public string? EmailAddress { get; set; }
public ICollection<ConditioningWorkout> ConditioningWorkouts { get; set; }
public ConditioningWorkout? ConditioningWorkout { get; set; }
public ICollection<Booking> Bookings { get; set; }
public ICollection<BikeWorkOut> BikeWorkOuts { get; set; }
public bool? IsDeleted { get; set; }
public ICollection<Notes>? Notes { get; set; }
public decimal? TB { get; set; }
public decimal? OP { get; set; }
public decimal? PU { get; set; }
public decimal? PB { get; set; }
public decimal? BP { get; set; }
public int Status { get; set; }
public bool? IsActive { get; set; }
public string? CreatedBy { get; set; }
public string? LastModifiedBy { get; set; }
public DateTime? LastUpdatedDate { get; set; }
public DateTime? CreatedDate { get; set; }
}
Team
public class Team
{
public int Id { get; set; }
public Guid? UserId { get; set; }
public Guid? TennantId { get; set; }
public string Name { get; set; }
public int? CoachId { get; set; }
public virtual Coach Coach { get; set; }
public ICollection<Student> Students { get; set;}
public bool? IsDeleted { get; set; }
public int? SessionId { get; set; }
public bool? IsActive { get; set; }
public string? CreatedBy { get; set; }
public string? LastModifiedBy { get; set; }
public DateTime? LastUpdatedDate { get; set; }
public DateTime? CreatedDate { get; set; }
}
I think I need to have some link back from the Student to the session but because they can block book sessions and team level I dont no how to achieve this.
It looks like a Session has a Team(s?) and a Team has a Student(s), so it's reasonably straight forward:
context.Sessions.Include(s => s.Team).ThenInclude(t => t.Students)
.Where(s => s.StartDate == new DateTime(2021, 11, 5))
This gets you a collections of sessions that should have their Team property populated with a Team, and in turn that Team has a Students collection that is populated with Students

SQL to Entity Framework, inner SELECT with multiple JOINs

I have the following SQL query that I need to rewrite to Entity Framework with navigation properties. Basically, and Employee has a number of tasks that someone can volunteer to do. I'm trying to find all employees that have at least one volunteer assigned to any task.
SELECT j.noTasks, e.*
FROM Employee e
LEFT JOIN
(SELECT e.id, COUNT(vt.TaskId) as "noTasks"
FROM Employee e
LEFT JOIN Task t on e.id = t.EmployeeId
LEFT JOIN VolunteerTask vt on vt.TaskId = t.id
GROUP BY e.id) j
ON e.id = j.id AND noTasks > 0
The troubling part is the inner SELECT. I've read the documentation, but I'm having difficulties understanding it.
Employee class:
public partial class Employee : IEntity
{
public int id { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; }
[StringLength(100)]
public string WorkPlace { get; set; }
public int EmployeeTypeId { get; set; }
[Required]
[StringLength(11)]
public string OrganizationNumber { get; set; }
[StringLength(20)]
public string Telephone { get; set; }
[Required]
[StringLength(100)]
public string StreetAddress { get; set; }
[StringLength(200)]
public string CoAddress { get; set; }
[Required]
[StringLength(20)]
public string ZipCode { get; set; }
[StringLength(200)]
public string City { get; set; }
[StringLength(200)]
public string HomePage { get; set; }
[Required]
[StringLength(200)]
public string ContactPerson { get; set; }
[StringLength(30)]
public string ContactPhone { get; set; }
[StringLength(30)]
public string ContactPhone2 { get; set; }
[StringLength(200)]
public string ContactEmailAddress { get; set; }
public DateTime RegisteredDate { get; set; }
public virtual EmployeeType EmployeeType { get; set; }
[Required]
public UserStatus Status { get; set; }
public string ImageFileName { get; set; }
}
Task class:
public partial class Task : IEntity
{
public Task()
{
VoluntaryTasks = new HashSet<VoluntaryTask>();
TaskInterest = new HashSet<TaskInterest>();
TaskCalendarItems = new HashSet<TaskCalendarItem>();
}
public int id { get; set; }
[StringLength(100)]
public string Name { get; set; }
public int EmployeeId { get; set; }
public int AreaId { get; set; }
[Column(TypeName = "ntext")]
public string Description { get; set; }
public int NoOfVolunteers { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? PublicationDate { get; set; }
public DateTime EndDate { get; set; }
[Required]
[StringLength(200)]
public string ContactPerson { get; set; }
[Required]
[StringLength(30)]
public string ContactTelephone { get; set; }
[StringLength(30)]
public string ContactTelephone2 { get; set; }
[StringLength(100)]
public string EmailAddress { get; set; }
public bool isPublished { get; set; }
public bool NotificationMailSent { get; set; }
public double? Latitude { get; set; }
public double? Longitude { get; set; }
public int Priority { get; set; }
public RecordStatus RecordStatus { get; set; }
public virtual Area Area { get; set; }
public string LocationDescription {get; set;}
public virtual Employee Employee { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<VoluntaryTask> VoluntaryTasks { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<TaskInterest> TaskInterest { get; set; }
public virtual ICollection<TaskLanguageSkill> TaskLanguageSkills { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<TaskCalendarItem> TaskCalendarItems { get; set; }
}
VoluntaryTask class:
public partial class VoluntaryTask
{
//[Key]
[Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int VoluntaryId { get; set; }
//[Key]
[Column(Order = 1)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int TaskId { get; set; }
//[Key]
public VoluntaryTaskStatus Status { get; set; }
public DateTime StartDate { get; set; }
public DateTime? EndDate { get; set; }
public virtual Task Task { get; set; }
public virtual Voluntary Voluntary { get; set; }
}

Map navigation properties in Dapper.Net using stored procedure

I am using Dapper.Net to get data from SQL Server database.
Here is my POCO classes
public partial class Production
{
public System.Guid ProductionId { get; set; }
public System.Guid SurveyId { get; set; }
public Nullable<int> PercentComplete { get; set; }
public string CompletedBy { get; set; }
public string DeliverTo { get; set; }
public virtual SurveyJob SurveyJob { get; set; }
}
public partial class SurveyJob
{
public SurveyJob()
{
this.Productions = new HashSet<Production>();
}
public System.Guid SurveyId { get; set; }
public string JobTitle { get; set; }
public Nullable<int> Status { get; set; }
public Nullable<int> JobNumber { get; set; }
public Nullable<System.DateTime> SurveyDate { get; set; }
public Nullable<System.DateTime> RequiredBy { get; set; }
public virtual ICollection<Production> Productions { get; set; }
}
I want to get all productions along with their SurveyJob information. Here is my SQL query in the stored procedure which returns these columns
SELECT
P.ProductionId, S.SurveyId,
P.PercentComplete, P.CompletedBy, P.DeliverTo,
S.JobTitle, S.JobNumber, S.RequiredBy, S.Status, S.SurveyDate
FROM
dbo.Production P WITH(NOLOCK)
INNER JOIN
dbo.SurveyJob S WITH(NOLOCK) ON S.SurveyId = P.SurveyId
Problem is that I am getting Production data but SurveyJob object is null.
Here is my c# code
var result = await Connection.QueryAsync<Production>("[dbo].[GetAllProductions]", p, commandType: CommandType.StoredProcedure);
I am getting SurveyJob object null as shown in image.
Need help. What I am doing wrong?
Your model is malformed for the query you executed, your query will return a plain object (dapper will always return plain objects), so you need a class with all the properties you're selecting.
Change your model to this:
public partial class ProductionSurvey
{
public System.Guid ProductionId { get; set; }
public System.Guid SurveyId { get; set; }
public Nullable<int> PercentComplete { get; set; }
public string CompletedBy { get; set; }
public string DeliverTo { get; set; }
public System.Guid SurveyId { get; set; }
public string JobTitle { get; set; }
public Nullable<int> Status { get; set; }
public Nullable<int> JobNumber { get; set; }
public Nullable<System.DateTime> SurveyDate { get; set; }
public Nullable<System.DateTime> RequiredBy { get; set; }
}

LINQ: Group by and Join

I have 2 models:
public partial class Movie
{
public Movie()
{
TimeTables = new HashSet<TimeTable>();
}
[Key]
public int MovieId { get; set; }
public string MovieName { get; set; }
public int MovieGenre { get; set; }
public string MoviePicture { get; set; }
public string MovieDescription { get; set; }
public string MovieShortText { get; set; }
public bool? MovieIs3d { get; set; }
public bool? MovieIsImax { get; set; }
public int MovieLanguage { get; set; }
public bool? MovieSubtitled { get; set; }
public int? MovieMinimalAge { get; set; }
public bool? MovieHasDrugs { get; set; }
public bool? MovieHasViolence { get; set; }
public bool? MovieHasSex { get; set; }
public bool? MovieHasSwearing { get; set; }
public bool? MovieIsScary { get; set; }
public bool? MovieHasDiscrimination { get; set; }
public string MovieTrailer { get; set; }
public int MovieLength { get; set; }
public int? Genre_GenreId { get; set; }
public int? Language_LanguageId { get; set; }
public virtual Genre Genre { get; set; }
public virtual Language Language { get; set; }
public virtual ICollection<TimeTable> TimeTables { get; set; }
}
And:
public partial class TimeTable
{
public TimeTable()
{
Reservations = new HashSet<Reservation>();
}
public int TimeTableId { get; set; }
public int MovieId { get; set; }
public int RoomId { get; set; }
public int SeatsAvaible { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public virtual Movie Movie { get; set; }
public virtual ICollection<Reservation> Reservations { get; set; }
public virtual Room Room { get; set; }
}
I want to show all the records from Movie which have one or more records in TimeTable and where StartDate.date == [given datetime].
With a simple query the movies are showing multiple times. I have tried a distinct() but that changes nothing.
Anybody here who have the solution?
Current query:
var times2 =
(from s in timetablerepo.TimeTables
orderby s.StartTime.TimeOfDay
where s.StartTime.Date == datetime.Date
select s).Distinct().ToList();
Why not start with movies first and filter by timetable:
var times = timetablerepo.Movies
.Where(m => m.TimeTables.Any(t => t.StartDate.Date == <yourdate>));

Categories

Resources