Aspire with MongoDB and EFCore #8118
Unanswered
JohnnyDevCraft
asked this question in
Q&A
Replies: 1 comment
-
Maybe this can help?
<ItemGroup>
<PackageReference Include="Aspire.MongoDB.Driver.v3" Version="9.2.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.4" />
<PackageReference Include="MongoDB.EntityFrameworkCore" Version="8.2.3" />
</ItemGroup>
public class MyDbContext(DbContextOptions<MyDbContext> options) : DbContext(options)
{
public DbSet<MyCakes> MyCakes { get; init; }
// https://www.mongodb.com/docs/entity-framework/current/fundamentals/indexes/
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<MyCakes>(p =>
{
p.HasIndex(x => x.TasteScore);
p.ToCollection("mycakes");
});
}
}
...
const string databaseName = "mydb";
// register IMongoClient and IMongoDatabase instances
builder.AddMongoDBClient(databaseName);
// register DbContext
// blazor? use factory: https://learn.microsoft.com/nb-no/ef/core/dbcontext-configuration/#use-a-dbcontext-factory
builder.Services.AddDbContext<MyDbContext>((sp, dbBuilder) =>
dbBuilder.UseMongoDB(sp.GetRequiredService<IMongoClient>(), databaseName));
var app = builder.Build();
// trigger OnModelCreating in MyDbContext
using var scope = app.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<MyDbContext>();
await db.Database.EnsureCreatedAsync();
...
app.MapGroup("/cakes").MapCakeEndpoints();
internal static class CakeEndpoints
{
public static RouteGroupBuilder MapCakeEndpoints(this RouteGroupBuilder group)
{
group.MapGet("", GetCakes)
.WithName("GetCakes")
.Produces<MyCakes[]>(StatusCodes.Status200OK);
return group;
}
public static async Task<IResult> GetCakes(MyDbContext db)
{
var cakes = await db.MyCakes.AsNoTracking().ToListAsync();
return Results.Ok(cakes);
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I'm trying to get EFCore running with MongoDB in Aspire, but I'm hitting a wall.
First, It took some digging to figure out compatible versions:
Then I had to try and get a context wired up. I have a single entity:
... which is set up in a context using this extension:
And this is my Context Class:
All of this is utilizing Aspire for Connection Strings, and my builder code looks like this:
I can get the IMongoClient and the database, but when I call Ensure created it gives me the following error message:
I can't figure out what's causing the issue and I would love some advice.
Beta Was this translation helpful? Give feedback.
All reactions