C# 利用EntityFrameworkCore ORM方式操作MongoDB数据库
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 --prereleaseBaseDbContext基类
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/
相关文章
- Spring Boot中对接Twilio以实现发送验证码和验证短信码
- Spring Boot 3.5:这次更新让你连配置都不用写了,惊不惊喜?
- Spring Boot+Pinot实战:毫秒级实时竞价系统构建
- SpringBoot敏感配置项加密与解密实战
- SpringBoot 注解最全详解,建议收藏!
- Spring Boot 常用注解大全:从入门到进阶
- SpringBoot启动之谜:@SpringBootApplication如何让配置化繁为简
- Springboot集成Kafka原理_spring集成kafka的原理
- Spring Boot中@Data注解的深度解析与实战应用
- 大佬用1000字就把SpringBoot的配置文件讲的明明白白!
