You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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.

Step 1: Prepare Firebase Project & Service Account
  • 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.
Step 2: Install Required NuGet Packages

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
Step 3: Initialize Firestore Client

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.

Step 4: Insert a Document

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!");
}
Step 5: Query Documents

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}");
    }
}
Quick Troubleshooting Tips
  • 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 FirestoreDb as a singleton service to use dependency injection across your app

内容的提问来源于stack exchange,提问作者RnnLn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:34:39