This guide shows you how to create a .NET application that uses the EF Core Provider to connect to a MongoDB Atlas cluster. If you prefer to connect to MongoDB using another programming language, see our list of official MongoDB drivers.
EF Core 提供程序通过将数据映射到.NET对象来简化对MongoDB集群中数据的操作。
MongoDB Atlas 是完全托管的云数据库服务,可在 MongoDB 集群托管数据。 在本指南中,我们将向您介绍 如何开始使用自己的免费(无需信用卡)集群。
请按照以下步骤将 EF Core 提供应用程序连接到MongoDB Atlas 群集。
创建 MongoDB 集群
在 Atlas 中设置免费集群
To set up your Atlas free cluster required for this Get Started guide, complete the MongoDB Atlas Setup guide.
完成Atlas 指南中的步骤后,您已在 中部署了一个新的MongoDB cluster Atlas、一个新的数据库用户以及已加载到集群中的样本数据集。复制缓冲区中还有一个类似于以下内容的连接string :
"mongodb+srv://<username>:<password>@cluster0.abc.mongodb.net/?retryWrites=true&w=majority"
设置您的项目
从应用程序查询 MongoDB 集群
添加示例代码
打开项目基本目录中名为Program.cs的文件。 将以下示例代码复制到Program.cs中:
public class MflixDbContext : DbContext { public DbSet<Movie> Movies { get; init; } = null!; public static MflixDbContext Create(IMongoDatabase database) => new(new DbContextOptionsBuilder<MflixDbContext>() .UseMongoDB(database.Client, database.DatabaseNamespace.DatabaseName) .Options); public MflixDbContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Movie>().ToCollection("movies"); } } public class Movie { [] public ObjectId _id { get; set; } [] public string Title { get; set; } = null!; [] public string Rated { get; set; } = null!; [] public string Plot { get; set; } = null!; }
查询样本数据
在 shell 中运行以下命令。 它应该从样本数据集中打印电影“回到未来”的情节:
dotnet run entity-quickstart.csproj
提示
If your output is empty, ensure you have loaded the sample datasets into your cluster.
完成这些步骤后,您应该有一个有效的实体框架应用程序,它可以连接到MongoDB cluster 、对示例数据运行查询并打印结果。
后续步骤
在快速参考中了解如何使用 EF Core 提供程序执行常见操作。