0

I have the following class:

public class Home
{
    [Key]
    public string Name { get; set; }

    [ForeignKey("Header")]
    public int HeaderID { get; set; }

    public Content Header { get; set; }
}

public class Header 
{
    //...sone attributes

    public ICollection<Home> Homes { get; set; }
}

I can't get data till making the Header null

Home item= BookingContext.Home.Include("Slides").FirstOrDefault();
item.Header = null;

is there any better way because I think I'm not in the correct way.

Nouh Belahcen
  • 774
  • 1
  • 11
  • 36
  • 3
    The question is unclear. What does `I can't get data till making the Header null` mean? Clearly, you're loading an `item` otherwise you'd get a NullReferenceException – Panagiotis Kanavos Aug 27 '20 at 09:15
  • @PanagiotisKanavos the problem is when I get data from the database the navigation properties it's like looping on when retrieving data because header has List of home. – Nouh Belahcen Aug 27 '20 at 09:46
  • @NoahLc that's the opposite of what you wrote, but still unclear and possibly *not* what's happening. What you wrote first means that no data is loaded. What you wrote now talks about an infinite loop, without showing any looping. What's the actual problem? – Panagiotis Kanavos Aug 27 '20 at 09:57
  • Are you getting a *JSON.NET* error perhaps, complaining about a self-referencing loop? That has nothing to do with Entity Framework. To avoid this, [tell Json.Net to ignore the loop](https://stackoverflow.com/questions/19467673/entity-framework-self-referencing-loop-detected) – Panagiotis Kanavos Aug 27 '20 at 10:00
  • @PanagiotisKanavos Sorry for my bad explanation, your answer is the solution, thanks. you can put it as an answer to accept it. – Nouh Belahcen Aug 27 '20 at 10:25

1 Answers1

-1

Use .Load() method:

using (var context = new BloggingContext())
{
    var post = context.Posts.Find(2);

    // Load the blog related to a given post.
    context.Entry(post).Reference(p => p.Blog).Load();

    // Load the blog related to a given post using a string.
    context.Entry(post).Reference("Blog").Load();

    var blog = context.Blogs.Find(1);

    // Load the posts related to a given blog.
    context.Entry(blog).Collection(p => p.Posts).Load();

    // Load the posts related to a given blog
    // using a string to specify the relationship.
    context.Entry(blog).Collection("Posts").Load();
}

More about Explicitly Loading https://learn.microsoft.com/en-us/ef/ef6/querying/related-data

Roman Ryzhiy
  • 1,540
  • 8
  • 5