❔ Initializing a relation in Entity Framework Core?

public class Post : Model
{
public string Slug { get; set; }
public string? Name { get; set; }
public string? Content { get; set; }
public bool Draft { get; set; } = true;
public DateTime PublishedAt { get; set; } = DateTime.Now;

public User User { get; set; }
public Blog Blog { get; set; }
public ICollection<Comment>? Comments { get; set; }
public ICollection<Label>? Labels { get; set; }

public Post(string slug, string? name, string? content) : base()
{
Slug = slug;
Name = name;
Content = content;
}
}
public class Post : Model
{
public string Slug { get; set; }
public string? Name { get; set; }
public string? Content { get; set; }
public bool Draft { get; set; } = true;
public DateTime PublishedAt { get; set; } = DateTime.Now;

public User User { get; set; }
public Blog Blog { get; set; }
public ICollection<Comment>? Comments { get; set; }
public ICollection<Label>? Labels { get; set; }

public Post(string slug, string? name, string? content) : base()
{
Slug = slug;
Name = name;
Content = content;
}
}
How can I initialize User and Blog with EntityFrameworkCore?
12 Replies
Timo Martinson
Timo MartinsonOP16mo ago
This is my DataContext:
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options) { }

public DbSet<User> Users { get; set; }
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<Comment> Comments { get; set; }
public DbSet<Label> Labels { get; set; }
}
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options) { }

public DbSet<User> Users { get; set; }
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<Comment> Comments { get; set; }
public DbSet<Label> Labels { get; set; }
}
blueberriesiftheywerecats
Introduction to relationships - EF Core
How to configure relationships between entity types when using Entity Framework Core
blueberriesiftheywerecats
u need to have foreign id inside your models and setup OnModelCreating method
Angius
Angius16mo ago
Either use IDs, or pass a tracked entity
var blog = await _ctx.Blogs.FindAsync(blogId);
var user = await _ctx.Users.FindAsync(userId);

var post = new Post {
// ...
Blog = blog,
User = user,
};

_ctx.Posts.Add(post);
await _ctx.SaveChangesAsync();
var blog = await _ctx.Blogs.FindAsync(blogId);
var user = await _ctx.Users.FindAsync(userId);

var post = new Post {
// ...
Blog = blog,
User = user,
};

_ctx.Posts.Add(post);
await _ctx.SaveChangesAsync();
or
var post = new Post {
// ...
BlogId = blogId,
UserId = userId,
};

_ctx.Posts.Add(post);
await _ctx.SaveChangesAsync();
var post = new Post {
// ...
BlogId = blogId,
UserId = userId,
};

_ctx.Posts.Add(post);
await _ctx.SaveChangesAsync();
Timo Martinson
Timo MartinsonOP16mo ago
how to use IDs in the constructor?!
Angius
Angius16mo ago
Uh, just add them...? Or don't have a constructor
Timo Martinson
Timo MartinsonOP16mo ago
ok, thanks! but how to reference _ctx ? where do I get _ctx from?
Angius
Angius16mo ago
It's your database context Inject it
Timo Martinson
Timo MartinsonOP16mo ago
could you show me some code?
Angius
Angius16mo ago
[ApiController]
[Route("[controller]")]
public class StuffController
{
private readonly MyDbContext _ctx;
public StuffController(MyCbContext ctx)
{
_ctx = ctx;
}

[HttpGet]
public async Task<IActionResult>([FromQuery] int id)
{
var thing = await _ctx.Things.FindAsync(id);
return Ok(thing);
}
}
[ApiController]
[Route("[controller]")]
public class StuffController
{
private readonly MyDbContext _ctx;
public StuffController(MyCbContext ctx)
{
_ctx = ctx;
}

[HttpGet]
public async Task<IActionResult>([FromQuery] int id)
{
var thing = await _ctx.Things.FindAsync(id);
return Ok(thing);
}
}
Timo Martinson
Timo MartinsonOP16mo ago
nice. thank you!!! 🙂
Accord
Accord16mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server