如何使用C#连接Firestore数据库并实现数据查询与插入?
Hey there! Let's walk through getting your C# app connected to Firestore, and cover basic query and insert operations—this should get you up and running smoothly.
- Head to your Firebase Console, select your target project
- Navigate to Project Settings > Service Accounts
- Click Generate New Private Key, download the JSON file. Keep this file secure—it’s your app’s credential to authenticate with Firestore.
In your C# project (console app, ASP.NET Core, etc.), install the official Firebase Admin SDK via NuGet:
# Using Package Manager Console Install-Package FirebaseAdmin # Or using .NET CLI dotnet add package FirebaseAdmin
First, load your service account JSON and initialize the Firebase app. Here’s a sample for a console application:
using FirebaseAdmin; using Google.Apis.Auth.OAuth2; using Google.Cloud.Firestore; class Program { // Change Main to async for async operations static async Task Main(string[] args) { // Initialize Firebase Admin SDK with your service account key FirebaseApp.Create(new AppOptions() { Credential = GoogleCredential.FromFile("C:/path/to/your/service-account-file.json"), }); // Get Firestore database instance (replace with your project ID) FirestoreDb db = FirestoreDb.Create("your-firebase-project-id"); Console.WriteLine("Connected to Firestore successfully!"); // Call insert/query methods here await AddUserAsync(db); await QueryUsersOver25Async(db); } }
Note: Replace the JSON file path and project ID with your actual values. You can find your project ID in Firebase Console > Project Settings > General.
Let’s create a simple model class to map to a Firestore collection, then add a document:
// Model class that matches Firestore document structure [FirestoreData] public class User { [FirestoreProperty] public string Name { get; set; } [FirestoreProperty] public int Age { get; set; } [FirestoreProperty] public string Email { get; set; } } // Async method to insert a user static async Task AddUserAsync(FirestoreDb db) { CollectionReference usersCollection = db.Collection("users"); User newUser = new User { Name = "Jane Smith", Age = 28, Email = "jane.smith@example.com" }; // Add document with auto-generated ID await usersCollection.AddAsync(newUser); // Or add with a custom ID: await usersCollection.Document("jane-smith").SetAsync(newUser); Console.WriteLine("New user added to Firestore!"); }
Here’s how to fetch a single document by ID, and query multiple documents with a filter:
// Get a specific user by document ID static async Task<User> GetUserByIdAsync(FirestoreDb db, string userId) { DocumentReference userDoc = db.Collection("users").Document(userId); DocumentSnapshot snapshot = await userDoc.GetSnapshotAsync(); if (snapshot.Exists) { User user = snapshot.ConvertTo<User>(); Console.WriteLine($"Found user: {user.Name} ({user.Email})"); return user; } else { Console.WriteLine("User not found in Firestore."); return null; } } // Query all users older than 25 static async Task QueryUsersOver25Async(FirestoreDb db) { Query ageFilterQuery = db.Collection("users").WhereGreaterThan("Age", 25); QuerySnapshot results = await ageFilterQuery.GetSnapshotAsync(); Console.WriteLine("\nUsers over 25:"); foreach (DocumentSnapshot doc in results.Documents) { User user = doc.ConvertTo<User>(); Console.WriteLine($"- {user.Name}, Age: {user.Age}"); } }
- Double-check the service account JSON path—use an absolute path for testing if relative paths cause issues
- Ensure your service account has the Cloud Datastore User role (verify in Google Cloud Console > IAM & Admin > IAM)
- For ASP.NET Core apps, register
FirestoreDbas a singleton service to use dependency injection across your app
内容的提问来源于stack exchange,提问作者RnnLn

