Uploaded image for project: 'Entity Framework'
  1. Entity Framework
  2. EF-64

The include method throws an exception

    XMLWordPrintableJSON

Details

    • Icon: Bug Bug
    • Resolution: Works as Designed
    • Icon: Unknown 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);
      });

      Attachments

        Activity

          People

            Unassigned Unassigned
            maghawry.hussein20@gmail.com Maghawry Hussein
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved:

              PagerDuty