I have the following data model:
public class Bubble
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection <Level> Children { get; set; }
}
public class Level
{
public int Id { get; set; }
public int BubbleId { get; set; }
public int? ParentId { get; set; }
public string Name { get; set; }
public Bubble Bubble { get; set; }
public Level Parent { get; set; }
public virtual ICollection<Level> Children { get; set; }
}
I want to store multiple sets of hierarchical data. Each set is owned by a bubble that contains levels (nodes). A level can either have it's self reference (parent) set to null (head of tree) or another level (sub node of parent) .
Now my problem is, that technically a level can have a parent (self reference) that does belong to another bubble. That should be impossible.
How can i make sure, that only levels with the same BubbleId FK can be assigned as a parent?
BubbleId
should be part of Level
's primary key, so that other levels referring to it will be guaranteed to have the same BubbleId
:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Level>()
.HasKey(l => new { l.Id, l.BubbleId });
modelBuilder.Entity<Level>()
.Property(l => l.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<Level>()
.HasMany(l => l.Children)
.WithOptional(l => l.Parent)
.HasForeignKey(l => new { l.ParentId, l.BubbleId });
}