Using EFCore 8, Code first.
I have two Entities, Student and Guardian. What I want is to have an simple way to differentiate between Custodial and NonCustodial relationships.
So I have Student:
public class Student:Entity {
public int Id {get;set;}
... etc
public virtual ICollection<Guardian> CustodialGuardians {get;set;}
public virtual ICollection<Guardian> NonCustodialGuardians {get;set;}
}
and Guardian:
public class Guardian:Entity {
public int Id {get;set;}
... etc
public virtual ICollection<Student> CustodialGuardianOf {get;set;}
public virtual ICollection<Student> NonCustodialGuardianOf {get;set;}
}
and then I Created a simple Join entity:
public class CustodialStudentGuardian
{
public virtual Guardian ParentGuardian { get; set; } = default!;
public virtual Student Student { get; set; } = default!;
public bool Custodial {get;set;}=default!;
}
and Configuration:
modelBuilder.Entity<Student>(e =>
e.HasMany(s => s.CustodialGuardians)
.WithMany(s => s.CustodialGuardianOf)
.UsingEntity<CustodialStudentGuardian>(c =>
{
c.HasOne(c => c.Student).WithOne();
c.HasOne(c => c.ParentGuardian).WithOne();
c.HasDiscriminator(d=>d.Custodial).HasValue(true);
});
});
I repeat the above configuration for noncustodial where the value is set to false.
This isn’t working, but I think maybe I’m close. I’m not even attached to doing it this way – I’d just like a way to be able to have a distinction between a custodial and non custodial parent. I’d prefer to have a single property and a query filter or something on the entity, rather than having to add a property for both custodial and non. Like I could query if parent is custodial rather than asking if the student has any custodial parents and is this parent one of them.
I know that I could get this done with extension methods and/or linq queries, but I was hoping I could get it done by convention using relationships.
I’m still somewhat new to CSharp and EfCore, so forgive any incorrect terminology.