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
Related
My Club has many members so I have added the following virtual property Members my question is when I want to list the club members shouldn't adding just the virtual load this into lazy loading am using .net 5.0.1 at present.
var members = _context.Clubs.Include(c=>c.Members).Where(w => w.ClubId == tennantId ).ToList();
When I look at var members even when the members have been included it is zero even though the teannatId matches.
public class MSFSAddonDBContext : IdentityDbContext<ApplicationUser>
{
public MSFSAddonDBContext(DbContextOptions<MSFSAddonDBContext> options)
: base(options)
{
}
public DbSet<Club> Clubs { get; set; }
public virtual List<ApplicationUser>? Members { get; set; }
}
This is my controller method.
public void IActionResult ClubMembers()
{
var tennantId = GetTennantId().Result;
var members = _context.Clubs.Include(c=>c.Members).Where(w => w.ClubId == tennantId ).ToList();
return View(members);
}
There are two members references at top level and inside the clubs.
This is the club class
public class Club
{
public int Id { get; set; }
public Guid? TeannatId { get; set; }
public Guid? ClubId { get; set; }
public Guid? UserId { get; set; }
public string? Name { get; set; }
public string? Description { get; set; }
public string? Url { get; set; }
public int? ClubLikes { get; set; }
public int? ClubDislikes { get; set; }
public int? MembersCount { get; set; }
public string? Logo { get; set; }
public List<Flight>? Flights { get; set; }
public string? ThumbNail { get; set; }
public DateTimeOffset? GpdrRemoveRequestDate { get; set; }
public bool? isGpdrRemoveRequest { get; set; }
public DateTimeOffset? BannedTime { get; set; }
public TimeSpan? BanPeriod { get; set; }
public bool? isBanned { get; set; }
public bool? isActive { get; set; }
public bool? isDeleted { get; set; }
public DateTime? CreatedDate { get; set; }
public string? CreatedBy { get; set; }
public virtual List<ApplicationUser>? Members { get; set; }
}
Edit 2
This is the application user class.
public class ApplicationUser : IdentityUser
{
public enum UserTypeEnum
{
Guest=0,
User=1,
Author=2,
AddonOwner=3,
GroupOwner=5,
ClubMember=6,
ClubAdmin=7,
SuperAdmin=199,
BandUser=999
}
public string? FirstName { get; set; }
public string? LastName { get; set; }
public string? GamerTag { get; set; }
public bool? isOnline { get; set; }
public int? UserType { get; set; }
public Guid? TennantId { get; set; }
public Guid? ClubId { get; set; }
public List<Badges>? Badges { get; set; }
}
NB As always with ef the primary keys in all my tables are the Id column thanks
This is the first time I have attempted to join information from one database to the other. I have a accounting database and a regular site database. Trying to keep them separate. I have a page that shows Transactions but am getting the information for a few of the columns from the regular database by way of Id's. Below is my Model. I am showing nothing in the fields for the items in the other database.
public class Transaction
{
[Key]
public Guid TransactionId { get; set; }
public string Description { get; set; }
public int? CompanyId { get; set; }
public Guid? VendorId { get; set; }
public string InCheckNumber { get; set; }
public string OutCheckNumber { get; set; }
public string InvoiceNumber { get; set; }
public string PurchaseOrderNumber { get; set; }
public Guid LedgerAccountId { get; set; }
public decimal? DebitAmount { get; set; }
public decimal? CreditAmount { get; set; }
public DateTime TransactionDate { get; set; }
public string ModifiedBy { get; set; }
public DateTime? ModifiedDate { get; set; }
public string SavedDocument { get; set; }
public DateTime CreatedDate { get; set; }
public string CreatedBy { get; set; }
public bool IsCredit { get; set; }
public bool IsDebit { get; set; }
public Guid Type { get; set; }
[ForeignKey("LedgerAccountId")]
public LedgerAccount LedgerAccount { get; set; }
[ForeignKey("CompanyId")]
public CompanyNames Company { get; set; }
[ForeignKey("VendorId")]
public Vendors Vendor { get; set; }
}
I have added the 'using' of the General.Entities to this model. Is there something else i need to add for this?
Thanks in advance.
UPDATE:
See Question - Link to answer of question
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; }
}
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();
_quatationRepository = new QuatationRepository();
IList<Quatation> quatationObj = _quatationRepository.GetAll(quatation => quatation.IsDeleted == 0);
IList<QuatationModel> quatationModelObj = new List<QuatationModel>();
AutoMapper.Mapper.CreateMap<Quatation, QuatationModel>();
quatationModelObj = AutoMapper.Mapper.Map(quatationObj, quatationModelObj);
return quatationModelObj;
public partial class Quatation
{
public int QuatationId { get; set; }
public int FirmId { get; set; }
public int ItemId { get; set; }
public double Quantity { get; set; }
public decimal Price { get; set; }
public Nullable Dated { get; set; }
public Nullable IsDeleted { get; set; }
public Nullable CreatedDate { get; set; }
public Nullable CreatedBy { get; set; }
public Nullable ModifyDate { get; set; }
public Nullable ModifyBy { get; set; }
public virtual Firm Firm { get; set; }
public virtual Item Item { get; set; }
}
public class QuatationModel
{
public int QuatationId { get; set; }
public int? FirmId { get; set; }
public int ItemId { get; set; }
public double Quantity { get; set; }
public decimal Price { get; set; }
public DateTime? Dated { get; set; }
public int IsDeleted { get; set; }
public DateTime? CreatedDate { get; set; }
public int? CreatedBy { get; set; }
public DateTime? ModifyDate { get; set; }
public int? ModifyBy { get; set; }
//public string ItemName { get; set; }
//public List<SelectListItem> LstFirm { get; set; }
public virtual FirmModel Firm { get; set; }
public virtual ItemModel Item { get; set; }
//public IList<QuatationModel> LstQuatation { get; set; }
}
You have to make sure that properties with the same name have the same type. For example int on one side and Nullable on the other side will not work (IsDeleted).
Can you change your Nullable properties on the Quatation class to :
public partial class Quatation
{
public int QuatationId { get; set; }
public int FirmId { get; set; }
public int ItemId { get; set; }
public double Quantity { get; set; }
public decimal Price { get; set; }
public DateTime? Dated { get; set; }
public int IsDeleted { get; set; }
public DateTime? CreatedDate { get; set; }
public int? CreatedBy { get; set; }
public DateTime? ModifyDate { get; set; }
public int? ModifyBy { get; set; }
public virtual Firm Firm { get; set; }
public virtual Item Item { get; set; }
}
and then try to map i.e.
_quatationRepository = new QuatationRepository();
IList<Quatation> quatationObj = _quatationRepository.GetAll(quatation => quatation.IsDeleted == 0);
IList<QuatationModel> quatationModelObj = new List<QuatationModel>();
AutoMapper.Mapper.CreateMap<IList<Quatation>, IList<QuatationModel>>();
quatationModelObj = AutoMapper.Mapper.Map<IList<Quatation>, IList<QuatationModel>>(quatationObj.ToList());
return quatationModelObj;
Sorry for late reply
actually error occurred due to my relationship with another table.
i just remove remove foreign keys and update my edmx file.
then error is resolved .
its due to inconsistent data in all related tables.
Thanks for reply again .