Reputation: 294
I am currently working with Entity Framework Fluent API doing code-first approach mapping configurations, as I run into some confusing scenarios.
I have two classes: Organisation and Course.
public class Organisation {
public int Id { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
public class Course {
public int Id { get; set; }
public int OrganisationId { get; set; }
}
My mapping configurations look like:
public class OrganisationSchema : EntityTypeConfiguration<Organisation>
{
public OrganisationSchema()
{
ToTable(typeof(Organisation).Name);
HasKey(x => x.Id);
HasMany(x => x.Courses).WithRequired(x => x.Organisation).HasForeignKey(x => x.OrganisationId);
}
}
public class CourseSchema : EntityTypeConfiguration<Course>
{
public CourseSchema()
{
ToTable(typeof(Course).Name);
HasKey(x => x.Id);
HasRequired(x => x.Organisation).WithMany(x => x.Courses).HasForeignKey(x => x.OrganisationId);
}
}
My goal with my models is to have an Organisation with many Courses, while Course has only one Organisation.
Additionally if I delete an Organisation, I want EF to delete all Courses related. But if I delete a Course, one should not delete any Organisations.
Right now, in my mapping configurations, I explicit tell that one Organisation has many Courses and point out the foreign keys. And then I tell the exact same on one Course, just the other way around. Is this both-way mappings really nescessary, or could I skip one of the sides? How little mapping configuration is needed for EF to understand my goal? I really don't want to blow my code, neither my head.
According to my goal, I need some entity deletion handling. I know that this is configured by using the WillCascadeOnDelete()
extension, but I don't understand this extension. Where should I set the WillCascadeOnDelete() extension on my mapping configurations; which of the two sides - or both? How does it affect? And what is the boolean parameter value telling?
Upvotes: 2
Views: 89
Reputation: 220
public class Organisation {
public int Id { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
public class Course {
public int Id { get; set; }
public virtual Organisation Organisation { get; set; }
}
public class OrganisationSchema : EntityTypeConfiguration<Organisation>
{
public OrganisationSchema()
{
ToTable(typeof(Organisation).Name);
HasMany(x => x.Courses).WithRequired(x => .Organisation).WillCascadeOnDelete();
}
}
I think the above configuration should work for what you are asking. It uses some conventions for defining foreign key and keeps the mapping configuration to a minimum.
Upvotes: 1