Details
-
Bug
-
Resolution: Works as Designed
-
Unknown
-
None
-
Public Preview 1
-
None
Description
My project is a Todo Demo.
I have 2 classes Todo and Category with relations 1 to Many
When I try to get Todos with category it throws an exceptionÂ
// The Line which thows.
|
var result = await _context.Todos.Include(x=>x.Category).ToListAsync();
|
|
|
|
|
|
|
public class Category |
{
|
public ObjectId _id { get; set; } |
public string Name { get; set; } |
public ICollection<Todo> Todos { get; set; } |
}
|
|
|
public class Todo |
{
|
public ObjectId _id { get; set; } |
public string Name { get; set; } = null!; |
public string Description { get; set; } = null!; |
public bool IsDone { get; set; } |
public ObjectId CategoryId { get; set; } |
public Category Category { get; set; } |
}
|
|
|
public class TodoDbContext:DbContext |
{
|
public DbSet<Todo> Todos { get; init; } = null!; |
public DbSet<Category> Categories { get; init; } = null!; |
|
|
public TodoDbContext(DbContextOptions<TodoDbContext> options):base(options) |
{
|
|
}
|
|
|
protected override void OnModelCreating(ModelBuilder modelBuilder) |
{
|
base.OnModelCreating(modelBuilder);
|
modelBuilder.Entity<Todo>()
|
.HasOne(t => t.Category)
|
.WithMany(c => c.Todos)
|
.HasForeignKey(t => t.CategoryId)
|
.IsRequired();
|
|
|
modelBuilder.Entity<Category>()
|
.HasMany(c => c.Todos)
|
.WithOne(t => t.Category);
|
|
|
}
|
}
|
|
|
builder.Services.AddDbContext<TodoDbContext>(opt =>
|
{
|
var database = new MongoClient(builder.Configuration.GetConnectionString("Default")).GetDatabase("Todos"); |
opt.UseMongoDB(database.Client, database.DatabaseNamespace.DatabaseName);
|
});
|