C
C#5mo ago
Anoos

One-to-many relationships - EF

Hi guys might be a silly question but im confused, if i had a relationship like this
// Principal (parent)
public class Blog
{
public int Id { get; set; }
public ICollection<Post> Posts { get; } = new List<Post>(); // Collection navigation containing dependents
}

// Dependent (child)
public class Post
{
public int Id { get; set; }
public int BlogId { get; set; } // Required foreign key property
public Blog Blog { get; set; } = null!; // Required reference navigation to principal
}
// Principal (parent)
public class Blog
{
public int Id { get; set; }
public ICollection<Post> Posts { get; } = new List<Post>(); // Collection navigation containing dependents
}

// Dependent (child)
public class Post
{
public int Id { get; set; }
public int BlogId { get; set; } // Required foreign key property
public Blog Blog { get; set; } = null!; // Required reference navigation to principal
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.HasMany(e => e.Posts)
.WithOne(e => e.Blog)
.HasForeignKey(e => e.BlogId)
.IsRequired();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.HasMany(e => e.Posts)
.WithOne(e => e.Blog)
.HasForeignKey(e => e.BlogId)
.IsRequired();
}
when i query posts i still get the data blog without using include. should i confiure the default behavior to no tracking?
8 Replies
Salman
Salman5mo ago
normally in order to fetch the navigation property as well you would need to use the include :
c#
var postsIncludingBlog = _context.Posts.Include(p => p.Blog);
c#
var postsIncludingBlog = _context.Posts.Include(p => p.Blog);
Anoos
AnoosOP5mo ago
so if i do something like this var postsIncludingBlog = _context.Posts.ToList(); blog will be null?
Salman
Salman5mo ago
yes
Anoos
AnoosOP5mo ago
when im testing it in my code im getting the values without using include
Salman
Salman5mo ago
strange..are you passing the blog explicitly while creating the Post ?
Anoos
AnoosOP5mo ago
no i was just querying the table directly I overlooked this part and i think this is whats happening correct me if im wrong. in the same code block i just noticed it was first querying blogs table then later it queries posts so it wasn't null because blogs data is available in the context?
Joschi
Joschi5mo ago
If the data is being tracked by the change tracker of your current context instance it will be filled from there. So if you test data fetching or even any kind of manipulation with an DBContext, you should either call context.ChangeTracker.Clear() or create a new context between operations.
Anoos
AnoosOP5mo ago
understood thank you guys! :meowheart:
Want results from more Discord servers?
Add your server