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

MongoDB结合C#实现嵌套类数据建模的优化方案咨询

Hey there! As someone who’s worked with MongoDB and C# for a few years, I totally get where you’re coming from—nesting entire classes inside others can quickly make your code feel clunky, especially as you add more business use cases. Let’s break down two standard MongoDB data modeling approaches that’ll clean up your code, plus some best practices for structuring your C# classes.

1. Embedded Documents (Denormalized Model)

This is great if you almost always query an Episode and need its associated Series info at the same time. Instead of treating them as separate entities, you embed the Series data directly inside the Episode document. You can still keep the Series class for reusability, but we’ll tweak the naming and structure to avoid confusion:

// Keep each class in its own file for better organization!
public class SeriesDetails
{
    // No need for an [BsonId] here unless you plan to reference this standalone elsewhere
    public string Name { get; set; }
    public int TotalSeasons { get; set; }
    public int TotalEpisodesPerSeason { get; set; }
}

public class Episode
{
    [BsonId]
    public Guid Id { get; set; }
    public string Name { get; set; }
    public TimeSpan Length { get; set; } // Use TimeSpan instead of string for better type safety
    public int SeasonNumber { get; set; } // Follow C# PascalCase naming conventions
    public int EpisodeNumber { get; set; }
    public SeriesDetails SeriesInfo { get; set; } // Clearer name than "Series_Id"
}

When creating an episode, the code stays clean and readable:

var episode = new Episode
{
    Id = Guid.NewGuid(),
    Name = "Example Episode",
    Length = TimeSpan.FromMinutes(45),
    SeasonNumber = 5,
    EpisodeNumber = 1,
    SeriesInfo = new SeriesDetails
    {
        Name = "Example Series",
        TotalSeasons = 5,
        TotalEpisodesPerSeason = 10
    }
};

2. Referenced Documents (Normalized Model)

Use this if multiple episodes belong to the same series, or if you need to update series details independently (without editing every episode). Here, you only store the Series ID in the Episode instead of the entire object—this keeps your Episode class lean and avoids duplicate data:

// Series.cs
public class Series
{
    [BsonId]
    public Guid Id { get; set; }
    public string Name { get; set; }
    public int TotalSeasons { get; set; }
    public int TotalEpisodesPerSeason { get; set; }
}

// Episode.cs
public class Episode
{
    [BsonId]
    public Guid Id { get; set; }
    public string Name { get; set; }
    public TimeSpan Length { get; set; }
    public int SeasonNumber { get; set; }
    public int EpisodeNumber { get; set; }
    public Guid SeriesId { get; set; } // Only store the reference ID
}

Usage example (assuming you have MongoDB collections for both):

// First create and save the series
var mySeries = new Series
{
    Id = Guid.NewGuid(),
    Name = "Example Series",
    TotalSeasons = 5,
    TotalEpisodesPerSeason = 10
};
await _seriesCollection.InsertOneAsync(mySeries);

// Then create the episode, linking to the series via ID
var myEpisode = new Episode
{
    Id = Guid.NewGuid(),
    Name = "Example Episode",
    Length = TimeSpan.FromMinutes(45),
    SeasonNumber = 5,
    EpisodeNumber = 1,
    SeriesId = mySeries.Id
};
await _episodeCollection.InsertOneAsync(myEpisode);

Bonus: Clean Up Your Code Structure

To avoid messy code as you add more use cases:

  • Separate classes into individual files: Put Episode.cs, Series.cs, etc., in a dedicated Models folder.
  • Follow C# naming conventions: Use PascalCase for property names (no underscores like Series_Id).
  • Use appropriate data types: Replace string-based Length with TimeSpan for type safety and better MongoDB storage.
  • Use MongoDB attributes intentionally: Use [BsonElement("series_id")] if you need to map a PascalCase property to a snake_case field in the database.

Pick the approach that fits your business needs: embedded documents for fast, joined queries; referenced documents for shared, updatable data.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 04:32:48