Only allow self reference to a model that has a reference to the same owner

c# entity-framework entity-framework-6

Question

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?

1
0
2/21/2019 1:22:32 PM

Popular Answer

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 });
}
0
2/21/2019 9:54:55 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow