Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6191473
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T02:46:20+00:00 2026-05-24T02:46:20+00:00

I need to represent a composite pattern with Entity Framework code first. How can

  • 0

I need to represent a composite pattern with Entity Framework code first. How can this be accomplished?
I’ve read a post about using a visitor pattern, but I think it should be done easily and less complex with Fluent API, but I don’t know how.

It saves correctly the data in the database but when I try to load it back again It brings wrong data.

var components = from p in ctx.LayerComponents.Include("ComponentsLayer").Include("Component") select p;

foreach (var p in components)
{
    Trace.WriteLine("------------------------------------------------------------------------------------------------");
    p.Apply();
}

This is my model so far:

public abstract class LayerComponents
{
    public LayerComponents()
    {
        Components = new List<Component>();
    }

    [Key]
    public int Id { get; set; }
    public string Description { get; set; }

    public ICollection<Component> Components { get; set; }
    public abstract void Apply();
    public abstract void AddLayer(LayerComponents component);
    public abstract void RemoveLayer(LayerComponents component);
    public abstract void AddComponent(Component component);
}

public class CompositeLayerComponents : LayerComponents
{
    public ICollection<LayerComponents> ComponentsLayer { get; set; }
    public int? ParentID { get; set; }
    public CompositeLayerComponents Parent { get; set; }

    public CompositeLayerComponents()
    {
        ComponentsLayer = new List<LayerComponents>();
    }

    public override void ApplyComponents()
    {
        foreach (LayerComponents lp in ComponentsLayer)
        {
            lp.ApplyComponents();
        }
        Trace.WriteLine("Inside: " + Description);
        foreach (var p in Components)
        {
            Trace.WriteLine("       Applying component: " + p.Key.ToString() + "-" + p.Value.ToString());
        }
        Trace.WriteLine("Done Applying Components in " + Description + Environment.NewLine);
    }

    public override void AddLayer(LayerComponents component)
    {
        ComponentsLayer.Add(component);
    }

    public override void RemoveLayer(LayerComponents component)
    {
        ComponentsLayer.Remove(component);
    }

    public override void AddComponent(Component component)
    {
        this.Components.Add(component);
    }
}

public class LeafLayerComponents : LayerComponents
{
    public override void ApplyComponents()
    {
        Trace.WriteLine("Inside: " + Description);
        foreach (var p in Components)
        {
            Trace.WriteLine("       Applying component: " + p.Key.ToString() + "-" + p.Value.ToString());
        }
        Trace.WriteLine("Done Applying Components in " + Description + Environment.NewLine);
    }

    public override void AddLayer(LayerComponents component)
    {
        throw new Exception("Can't add a layer to the LeafLayerComponents");
    }

    public override void RemoveLayer(LayerComponents component)
    {
        throw new Exception("Can't add a layer to the LeafLayerComponents");
    }

    public override void AddComponent(Component component)
    {
        Components.Add(component);
    }
}

public class Component
{
    [Key]
    public int Id { get; set; }
    [Required]
    protected string Description { get; set; }

    [Required]
    public int KeyValue { get; set; }

    [Required]
    public string Value { get; set; }
    [Required]
    public Guid userId { get; set; }
}

The problem is that when I load the database records, it doesn’t map correctly again in memory. For example:
If I save this

    root = new CompositeLayerComponents { Description = "root" };

        // Set building preferences
        var buildingComponentsLayer = new CompositeLayerComponents { buildingId = Guid.NewGuid(), Description = "buildingComponents" };
        buildingComponentsLayer.AddComponent(new Component { Key = 0, Value = "Concept2" });
        buildingComponentsLayer.AddComponent(new Component { Key = 1, Value = "1" });
        buildingComponentsLayer.AddComponent(new Component { Key = 2, Value = "true" });

        var floor1LayerComponents = new CompositeLayerComponents { Description = "floor1Components" };
        floor1LayerComponents.AddComponent(new Component() { Key = 0, Value = "Concept1" });
        floor1LayerComponents.AddComponent(new Component() { Key = 1, Value = "2" });
        floor1LayerComponents.AddComponent(new Component() { Key = 2, Value = "true" });

        var floor2LayerComponents = new CompositeLayerComponents { Description = "floor2Components" };
        floor2LayerComponents.AddComponent(new Component() { Key = 0, Value = "Concept1" });
        floor2LayerComponents.AddComponent(new Component() { Key = 1, Value = "2" });
        floor2LayerComponents.AddComponent(new Component() { Key = 2, Value = "false" });

        var officeComponentsLayer = new LeafLayerComponents { Description = "officeComponents" };
        officeComponentsLayer.AddComponent(new Component() { Key = 0, Value = "Concept1" });

        buildingComponentsLayer.AddComponentLayer(floor1LayerComponents);
        floor2LayerComponents.AddComponentLayer(officeComponentsLayer);
        buildingComponentsLayer.AddComponentLayer(floor2LayerComponents);
        root.AddComponentLayer(buildingComponentsLayer);

        ctx.LayerComponents.Add(root);
        ctx.SaveChanges();

It doesn’t load one root layer with one buildingLayerComponent inside which has 2 floorLayerComponents and one of that floorLayerComponents has one officeLayerComponent. That’s the problem, how to load that hierarchy back again.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T02:46:21+00:00Added an answer on May 24, 2026 at 2:46 am

    It is hard to follow your code because it is even not compilable but if your problem is that it doesn’t load whole hierarchy then it is not a problem it is a feature. EF doesn’t load relations automatically. You must tell it to do it and in hierarchical structures it is actually very hard.

    You can use eager loading:

    var root = context.LayerComponents.OfType<CompositeLayerComponsnts>().Include(c => c.ComponentsLayer).Where(c => c.ParentId == null);
    

    This query will load all top level composites and their direct layer components (only single level!).

    You can also use lazy loading but all your navigation properties must be marked as virtual. In such case EF will create separate query for loading each navigation property once accessed for the first time. In hierarchical structure this can result in a lot of database queries.

    I expect you will have many other problems with your code. For example if you expect that all three layers will use the same components they will not – each component will be added three times and if key represents its primary key it will have different value.

    You should probably read little bit about EF and how it works before you start to do complex mapping otherwise you will have a lot of troubles.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

We need to represent huge numbers in our application. We're doing this using integer
I need to represent this hierarchy in a JSON object. Can someone help me
I need to represent the unit of Percent per second using the JScience.org's JSR
I have 6000 data of district, subdistrict. I need to represent this on dependent
Need to represent a two column table. Maybe just for reference at this stage
I need to represent a table containing data about some tests and their results.
I need to represent certain data in following format using xml. root-> col1-item1 ->
I need to represent these mathematical equations in code and to solve them: 2x
I need to represent inheritance like Person/Student. How do you do that in LInqToSql?
I need to represent calculator key presses by the text for the keys to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.