Entity Framework Many to Many Relationship 3 Classes - entity-framework

Hi I have the three classes below. I'm trying achieve a many to many mapping with three classes. I have achieved many to many relationship between two classes but I'm trying to get another class in the mix. Below is the classes I have and a class representation of the relationship I'm trying to achieve.
public class Person
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmployeeId { get; set; }
public ICollection<Department> Departments { get; set; }
}
public class Department
{
public int ID { get; set; }
public string Name { get; set; }
public string DepartmentCode { get; set; }
public string Description { get; set; }
public ICollection<Person> Members { get; set; }
}
public class Role
{
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
Any hints on how to achieve the below would be helpful.
public class PersonRoleDepartment
{
public int PersonID { get; set; }
public int DepartmentID{ get; set; }
public int RoleID { get; set; }
}

public class Person
{
public int Id { get; set; }
public ICollection<PersonDepartmentRole> DepartmentRoles { get; set; }
}
public class Department
{
public int Id { get; set; }
public ICollection<PersonDepartmentRole> PersonRoles { get; set; }
}
public class Role
{
public int Id { get; set; }
public ICollection<PersonDepartmentRole> PersonDepartments { get; set; }
}
public class PersonDepartmentRole
{
[Key, Column( Order = 0 )]
public int PersonId { get; set; }
[ForeignKey( "PersonId" )]
[Required]
public virtual Person Person { get; set; }
[Key, Column( Order = 1 )]
public int DepartmentId { get; set; }
[ForeignKey( "DepartmentId" )]
[Required]
public virtual Department Department { get; set; }
[Key, Column( Order = 2 )]
public int RoleId { get; set; }
[ForeignKey( "RoleId" )]
[Required]
public virtual Role Role { get; set; }
}
Fluent API config:
var pdrConfig = modelBuilder.Entity<PersonDepartmentRole>()
.HasKey( pdr => new
{
pdr.PersonId,
pdr.DepartmentId,
pdr.RoleId
} );
pdrConfig.HasRequired( pdr => pdr.Department )
.WithMany( d => d.PersonRoles )
.HasForeignKey( pdr => pdr.DepartmentId );
pdrConfig.HasRequired( pdr => pdr.Person )
.WithMany( p => p.DepartmentRoles )
.HasForeignKey( pdr => pdr.PersonId );
pdrConfig.HasRequired( pdr => pdr.Role )
.WithMany( r => r.PersonDepartments )
.HasForeignKey( pdr => pdr.RoleId );
Note: all references from any of the primary entities to the others should route through your junction entity PersonDepartmentRole - if not, data inconsistencies can arise (e.g. I add a Department to a Person as well as a corresponding PersonDepartmentRole record to the DB, but then I remove the Department from the Person entity - the PersonDepartmentRole entity still remains)
Instead, if you want all departments for a person:
db.Person.DepartmentRoles.Select( dr => dr.Department ).Distinct()

In this construct, can a person be in a department but have no role? Or, can a department play a role but has no people? If not, how could this be accomplished

Related

.NET Core: How to merge nested one-to-many relations in dto

How could merge nested child entity in parent?
I have these three entities:
public class Faculty
{
public Guid Id { get; set; }
public string Name { get; set; }
public ICollection<Group> Groups { get; set; }
}
public class Group
{
public Guid Id { get; set; }
public string Name { get; set; }
public ICollection<User> Users { get; set; }
}
public class User
{
public Guid Id { get; set; }
public string Name { get; set; }
}
Expected results in ResultDto is:
public class ResultDto
{
public Guid FacultyId { get; set; }
public string FacultyName { get; set; }
public ICollection<User> Users { get; set; }
}
You're looking for SelectMany:
var results = context.Faculties.Select(f => new ResultDto
{
FacultyId = f.Id,
FacultyName = f.Name,
Users = f.Groups.SelectMany(g => g.Users).ToList()
}
This will run in EF-core versions like 5 and 6, also in 3, but slightly less efficiently.

Entity Framework Core - 3 tier relationship

I have to apply a set of relationships with a system that incorporates a messaging system.
I have the two of my domain object with one mapping object (for the many-to-many relationship):
public class User
{
public User()
{
UserMails = new List<UserMail>();
}
public int Id { get; set; }
public ICollection<UserMail> UserMails { get; set; }
}
public class Mail
{
public Mail()
{
UserMails = new List<UserMail>();
}
public int Id { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public ICollection<UserMail> UserMails { get; set; }
}
public class UserMail
{
public int Id { get; set; }
public int FromUserId { get; set; }
public User FromUser { get; set; }
public int ToUserId { get; set; }
public User ToUser { get; set; }
public int MailId { get; set; }
public Mail Mail { get; set; }
}
How would I configure this relationship using Fluent API such that there's a many to many relationship between User and Mail and Mail can have 2 foreign keys back to the UserFrom and UserTo?
Any help on this would be greatly appreciated.
If you are trying to model the relationship between a mail and its sender/recipient, then you don't need a many-to-many relation, or 2 foreign keys in your joining entity. Instead, you need 2 one-to-many relations like below -
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Mail> ReceivedMails { get; set; }
public ICollection<Mail> SentMails { get; set; }
}
public class Mail
{
public int Id { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public int SenderId { get; set; }
public User Sender { get; set; }
public int RecipientId { get; set; }
public User Recipient { get; set; }
}
and you can configure them as -
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Mail>()
.HasOne(p => p.Sender)
.WithMany(p => p.SentMails)
.HasForeignKey(p => p.SenderId)
.OnDelete(DeleteBehavior.NoAction);
builder.Entity<Mail>()
.HasOne(p => p.Recipient)
.WithMany(p => p.ReceivedMails)
.HasForeignKey(p => p.RecipientId)
.OnDelete(DeleteBehavior.NoAction);
}

How do I get a response based on two different IDs in my API?

public class Report
{
[Key]
public int ReportId { get; set; }
[ForeignKey("Subjects")]
public int SubjectId { get; set; }
public Subjects Subjects { get; set; }
[ForeignKey("Teacher")]
public int TeacherId { get; set; }
public Teacher Teacher { get; set; }
[ForeignKey("MarkType")]
public int MarkTypeId { get; set; }
public MarkType MarkType { get; set; }
}
public class Teacher
{
[Key]
public int TeacherId { get; set; }
[MaxLength(50)]
[Required]
public string FName { get; set; }
[MaxLength(50)]
[Required]
public string LName { get; set; }
}
public class Student
{
[Key]
public int StudentId { get; set; }
[MaxLength(50)]
[Required]
public string FName { get; set; }
[MaxLength(50)]
[Required]
public string LName { get; set; }
[ForeignKey("Grade")]
public int GradeId { get; set; }
public Grade Grade { get; set; }
}
public class Grade
{
[Key]
public int GradeId { get; set; }
public int StudentGrade { get; set; }
}
public class Subjects
{
[Key]
public int SubjectId { get; set; }
[MaxLength(50)]
[Required]
public string SubjectName { get; set; }
}
public class Terms
{
[Key]
public int TermId { get; set; }
public int Term { get; set; }
}
public class MarkType
{
[Key]
public int MarkTypeId { get; set; }
[MaxLength(20)]
[Required]
public string TypeName { get; set; }
}
public class StudentMark
{
[Key]
public int StudentMarkId { get; set; }
[ForeignKey("Report")]
public int ReportId { get; set; }
public Report Report { get; set; }
[ForeignKey("Student")]
public int StudentId { get; set; }
public Student Student { get; set; }
public int Mark { get; set; }
[ForeignKey("Terms")]
public int TermId { get; set; }
public Terms Terms { get; set; }
}
In the API I am making I want to have the ability to use two different IDs to get a more specific response.
var report = ReportDBContext.StudentMark
.Include(p => p.Student.Grade).Include(p => p.Report)
.Include(p => p.Terms).Include(a => a.Report.Subjects).Include(a => a.Terms)
.Include(a => a.Report.MarkType).Include(a => a.Report.Teacher).ToList();
This allowed me to get StudentMark as well as it's related entities but I want to have the ability to use The student's Id and the Term's Id to get a student's marks for that term and all the subjects related to the student. I am a beginner to Web API so please let me know if I need to add more context.
If you want to query by either StudentId or TermId, I suggest that you provide two different endpoints for these two different queries. Use LINQ Where to check your conditions.
public StudentMark[] GetMarksByStudentId(int studentId) {
return ReportDBContext.StudentMark
/* .Include(...) */
.Where(mark => mark.StudentId == studentId)
.ToArray();
}
public StudentMark[] GetMarksByTermId(int termId) {
return ReportDBContext.StudentMark
/* .Include(...) */
.Where(mark => mark.TermId == termId)
.ToArray();
}
If you want to query by StudentId and TermId simultaneously, introduce a query object to encapsulate your parameters. You can test for multiple conditions in the Where clause with AND &&.
public StudentMark[] FindMarks(StudentMarkQuery query) {
return ReportDBContext.StudentMark
/* .Include(...) */
.Where(mark => mark.StudentId == query.StudentId
&& mark.TermId == query.TermId)
.ToArray();
}
The StudentMarkQuery class is introduced so you can add additional parameters without changing the overall signature of the endpoint:
public class StudentMarkQuery {
public int StudentId { get; set; }
public int TermId { get; set; }
}

N to M relationship code first does not create the foreign key on the M-table

A SchoolclassCode can have many Pupils.
A Pupil can belong to many SchoolclassCodes.
This is an N to M relation.
I thought N to M relation work in code first by default.
But I also explicitly create the N to M relation here:
modelBuilder.Entity<SchoolclassCode>().
HasMany(c => c.Pupils).
WithMany(p => p.SchoolclassCodes).
Map(
m =>
{
m.MapLeftKey("SchoolclassCodeId");
m.MapRightKey("PupilId");
m.ToTable("SchoolclassCodePupil");
});
public class SchoolclassCode
{
public SchoolclassCode()
{
Pupils = new HashSet<Pupil>();
Tests = new HashSet<Test>();
}
public int Id { get; set; }
public string SchoolclassCodeName { get; set; }
public string SubjectName { get; set; }
public int Color { get; set; }
public string ClassIdentifier { get; set; }
public ISet<Pupil> Pupils { get; set; }
public ISet<Test> Tests { get; set; }
public Schoolyear Schoolyear { get; set; }
public int SchoolyearId { get; set; }
}
public class Pupil
{
public Pupil()
{
PupilsTests = new HashSet<PupilTest>();
SchoolclassCodes = new HashSet<SchoolclassCode>();
}
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Postal { get; set; }
public string City { get; set; }
public string Street { get; set; }
public ISet<PupilTest> PupilsTests { get; set; }
public ISet<SchoolclassCode> SchoolclassCodes { get; set; }
}
On the Pupil Table no foreign key is created at all, Why this?
For a many to many relationship, there is no foreign key on either side. The foreign keys are on the join table, which you have mapped to the table SchoolclassCodePupil:
modelBuilder.Entity<SchoolclassCode>().
HasMany(c => c.Pupils).
WithMany(p => p.SchoolclassCodes).
Map(m =>
{
m.MapLeftKey("SchoolclassCodeId");
m.MapRightKey("PupilId");
m.ToTable("SchoolclassCodePupil");
});
Entity Framework uses that junction table to determine what belongs in the somePupil.SchoolclassCodes set.

EF Adding an additional FK?

I have the following 2 entities:
public class Team
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Fixture> Fixtures { get; set; }
}
public class Fixture
{
public int Id { get; set; }
public Result Result { get; set; }
public int HomeTeamId { get; set; }
public int AwayTeamId { get; set; }
public virtual Team HomeTeam { get; set; }
public virtual Team AwayTeam { get; set; }
}
I have then mapped it like so:
public class FixtureMap : EntityTypeConfiguration<Fixture>
{
public FixtureMap()
{
HasRequired(x => x.AwayTeam).WithMany().HasForeignKey(x => x.AwayTeamId);
HasRequired(x => x.HomeTeam).WithMany().HasForeignKey(x => x.HomeTeamId);
}
}
But when I add a migration, EF is creating an additional FK and column to my Fixture table and I've no idea why? How can I tell it not too?
As you can see its added a column called Team_Id and created an FK from it even tho I have specified the relationship in the mapping?
use this code:
public class Team
{
public int Id { get; set; }
public string Name { get; set; }
[InverseProperty("HomeTeam")]
public virtual ICollection<Fixture> HomeFixtures { get; set; }
[InverseProperty("AwayTeam")]
public virtual ICollection<Fixture> AwayFixtures { get; set; }
}
public class Fixture
{
public int Id { get; set; }
public Result Result { get; set; }
public int HomeTeamId { get; set; }
public int AwayTeamId { get; set; }
[InverseProperty("HomeFixtures")]
[ForeignKey("HomeTeamId ")]
public virtual Team HomeTeam { get; set; }
[InverseProperty("AwayFixtures")]
[ForeignKey("AwayTeamId")]
public virtual Team AwayTeam { get; set; }
}
And :
public class FixtureMap : EntityTypeConfiguration<Fixture>
{
public FixtureMap()
{
HasRequired(x => x.AwayTeam).WithMany().HasForeignKey(x => x.AwayTeamId).willCascadeOnDelete(false);
HasRequired(x => x.HomeTeam).WithMany().HasForeignKey(x => x.HomeTeamId);
}
}