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.
TF Core プロバイダーは、.NET オブジェクトにデータをマッピングすることで、MongoDB クラスター内のデータの操作を簡素化します。
MongoDB Atlas は、MongoDB クラスターでデータをホストする完全管理クラウドデータベース サービスです。このガイドでは、独自の無料クラスター(クレジットカードは不要)を開始する方法を説明します。
F Core Provider アプリケーションを MongoDB Atlas クラスターに接続するには、以下の手順に従います。
MongoDB クラスターを作成する
Atlas で無料クラスターを設定する
To set up your Atlas free cluster required for this Get Started guide, complete the MongoDB Atlas Setup guide.
Atlas ガイドの手順を完了すると、Atlas に新しい MongoDB クラスターが配置され、新しいデータベースユーザーが作成され、クラスターにサンプル データセットがロードされます。また、コピー バッファには次のような接続文字列があります。
"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 で次のコマンドを実行します。 サンプル データセットから、映画「Back to the feature」のプロットが出力されます。
dotnet run entity-quickstart.csproj
Tip
If your output is empty, ensure you have loaded the sample datasets into your cluster.
これらの手順を完了すると、MongoDB クラスターに接続し、サンプル データに対してクエリを実行し、結果を出力する動作する Entity Framework アプリケーションが作成されます。
次のステップ
TF Core プロバイダーを使用して一般的な操作を実行する方法については、「 クイック リファレンス 」を参照してください。