Setup mongoDB with Entity Framework Core

Setup mongoDB with Entity Framework Core

Models

    public abstract class AbstractModel
    {
          public string Id { get; set; } = string.Empty;
          public DateTime? CreatedOn { get; set; }
          public string? CreatedBy { get; set; }
    }
    public sealed class User: AbstractModel
    {
          public string EmailAddress{ get; set; } = string.Empty;
          public string? FirstName{ get; set; }
          public Role[] Roles {get; set;} = [];
    }
     public sealed Record Role
    {
          public string Name {get; set; } = string.Empty;
    }

    Entity Type Builder – Configurations

    public static class UserConfiguration
    {
       public static void Configure(EntityTypeBuilder builder)
       {
          builder.Property(x => x.Id).HasConversion<ObjectId>().HasElementName("_id");
          builder.ToCollection("users")
          builder.Property(c => c.CreatedOn).HasElementName("_created");
          builder.Property(c => c.CreatedBy).HasElementName("_created_by");
          builder.Property(c => c.EmailAddress).HasElementName("email_address");
          builder.Property(c => c.FirstName).HasElementName("first_name");
        
         builder.OwnsOne(u => u.Roles, role =>
        {
              role .HasElementName("role");
              role .Property(c => c.Name).HasElementName("name");
        });
      }
    }

    Configuration of models

    public sealed class IAMDbContext (DbContextOptions options) : DbContext(options)
    {
       public DbSet Users { get; init; }
    
       protected override void OnModelCreating(ModelBuilder modelBuilder)
       { 
           UserConfiguration.Configure(modelBuilder.Entity<User>());
           base.OnModelCreating(modelBuilder);
       }
    }

    Register Context

    public static IServiceCollection RegisterContext(this IServiceCollection services,  strinc connectionstring, string databasename)
    {
       services.AddOptions();
       
       services.AddDbContext<IAMDbContext>(options => {
         options.UseMongoDB(connectionstring, databasename);
         options.EnableSensitiveDataLogging();
         options.EnableDetailedErrors();
         options.EnableSensitiveDataLogging(true);
         options.EnableServiceProviderCaching();
     });
    
     return services;
    }

    Comments

    No comments yet. Why don’t you start the discussion?

    Leave a Reply

    Your email address will not be published. Required fields are marked *