C# 利用EntityFrameworkCore ORM方式操作MongoDB数据库

C# 利用EntityFrameworkCore ORM方式操作MongoDB数据库

技术教程gslnedu2025-02-01 12:44:1413A+A-

The Entity Framework Core Provider simplifies operations on data in MongoDB clusters by mapping the data to .NET objects.

MongoDB Atlas is a fully-managed cloud database service that hosts your data on MongoDB clusters. In this guide, we show you how to get started with your own free (no credit card required) cluster.

Follow the steps below to connect your Entity Framework Core Provider application to a MongoDB Atlas cluster.

MongoDB.EntityFrameworkCore安装

dotnet add package MongoDB.EntityFrameworkCore --prerelease

BaseDbContext基类

 public class BaseDbContext: DbContext
 {

     protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
     {
         var connectionString = "mongodb://localhost:27017";
         optionsBuilder.UseMongoDB(connectionString, "sample_mflix");
     }
 }

Collection DbContext操作类

internal class MflixDbContext : BaseDbContext
{
    public DbSet<Movie> Movies { get; init; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Movie>().ToCollection("movies");
    }
}

Collection实体类

internal class Movie
{
    public ObjectId _id { get; set; }
    public string title { get; set; }
    public string rated { get; set; }
    public string plot { get; set; }
}

查询Collection数据

var db = new MflixDbContext();

  List<Movie> listMovie = db.Movies.Where(m => m.title == "Pluto").ToList();
Console.WriteLine(listMovie[0].plot);

删除Collection数据

 var db = new MflixDbContext();
 db.Movies.rtRemove(listMovie[0]);
 db.SaveChanges();

插入Collection数据

 db.Movies.Add(new Movie()
 {
     title = "Pluto",
     rated = "ia",
     plot = "asdd",
 });
 db.SaveChanges();

批量插入Collection数据

 var movies = new[]
 {
     new Movie()
     {
         _id = ObjectId.GenerateNewId(),
         title = "Pluto1",
         rated = "ia1",
         plot = "asdd1",
     },
     new Movie()
     {
         _id = ObjectId.GenerateNewId(),
         title = "Pluto2",
         rated = "ia2",
         plot = "asdd2",
     }
 };
 db.Movies.AddRange(movies);
 db.SaveChanges();

更新Collection数据

 Movie movie = db.Movies.Where(m => m.title == "Pluto").FirstOrDefault();
movie.title = "更新数据";
db.Movies.Update(movie);
db.SaveChanges();

静态运行效果图

参考文档

  • https://www.mongodb.com/docs/entity-framework/current/quick-start/
点击这里复制本文地址 以上内容由朽木教程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

朽木教程网 © All Rights Reserved.  蜀ICP备2024111239号-8