डाटा- लाइब्रेरी पार्ट 1. 1 : ईएफ कोर के साथ एएसबीसी सूची (हिन्दी (Hindi))

डाटा- लाइब्रेरी पार्ट 1. 1 : ईएफ कोर के साथ एएसबीसी सूची

Saturday, 06 December 2025

//

13 minute read

CARECACT सूची सबसे सरल और सबसे सरल तरीका है अपने माता पिता को जमा करने के लिए। यह सिर्फ अपने माता पिता के लिए संकेत है। यह क्या सबसे अधिक डेवलपर पहली बात है, और कभी-कभी यात्रा के लिए छोटे पेड़ों के लिए, यह अक्सर सही विकल्प है। इस लेख में कार्यान्वयन विवरण शामिल है, पर निष्क्रिय सीनेट के लिए और यूआई संरचनाओं को प्रदर्शित करने के लिए।

श्रेणी नेविगेशन


एजाजता की सूची क्या है?

SACACACT सूची मॉडल सबसे पहले विकासकर्ता तक पहुँचने के लिए पहुँच के लिए है, और अच्छी वजह से यह है। प्रत्येक नोड सिर्फ अपने माता पिता के लिए एक संदर्भ भंडारित करता है। यदि आप कभी एक परिवार का पेड़ बनाया है, तो आप इस पैटर्न को पहले से ही समझ लिया है।

कुंजी विशेषता: हर पंक्‍ति केवल अपने निकटतम माता - पिता के बारे में जानता हैबुज़ुर्गों या नाती - पोतों को ढूँढ़ने के लिए, आपको अनेक तलाशों या पुनरावर्तनों की ज़रूरत है ।

यह सबसे सामान्य रूप है और अच्छी तरह से समर्थित है ईएफ कोर का आत्म-पुंजन संबंध.

एंटिटी परिभाषा

एंटिटी बहुत सरल है - हम सिर्फ एक नलेबल खुद को जोड़ते हैं:

public class Comment
{
    public int Id { get; set; }
    public string Content { get; set; } = string.Empty;
    public string Author { get; set; } = string.Empty;
    public DateTime CreatedAt { get; set; }

    // Foreign key - which blog post this comment belongs to
    public int PostId { get; set; }
    public BlogPost Post { get; set; } = null!;

    // ========== ADJACENCY LIST: The hierarchy is defined by these three properties ==========

    // ParentCommentId is nullable because:
    // - Root-level comments (direct replies to the post) have NULL
    // - Nested replies have the ID of the comment they're replying to
    public int? ParentCommentId { get; set; }

    // Navigation property to load the parent comment when needed
    // Useful for breadcrumb trails: "Post > Comment by Alice > Comment by Bob"
    public Comment? ParentComment { get; set; }

    // Navigation property to load immediate children (NOT grandchildren!)
    // EF Core populates this when you use .Include(c => c.Children)
    // NOTE: This only gives you ONE level deep - you won't see replies to replies
    public ICollection<Comment> Children { get; set; } = new List<Comment>();
}

ईएफ कोर कॉन्फ़िगरेशन

विन्यास स्व-पुंजनिंग संबंध स्थापित करता है और महत्वपूर्ण रूप से सूची जोड़ता है हम सबसे अधिक बार चला जाएगा:

public class CommentConfiguration : IEntityTypeConfiguration<Comment>
{
    public void Configure(EntityTypeBuilder<Comment> builder)
    {
        builder.HasKey(c => c.Id);

        builder.Property(c => c.Content)
            .IsRequired()
            .HasMaxLength(10000);

        builder.Property(c => c.Author)
            .IsRequired()
            .HasMaxLength(200);

        // Standard relationship: comment belongs to a blog post
        // Cascade delete here is safe - deleting a post should remove all its comments
        builder.HasOne(c => c.Post)
            .WithMany(p => p.Comments)
            .HasForeignKey(c => c.PostId)
            .OnDelete(DeleteBehavior.Cascade);

        // ========== THE SELF-REFERENCING RELATIONSHIP ==========
        // This is what makes it an adjacency list - each comment points to its parent

        builder.HasOne(c => c.ParentComment)
            .WithMany(c => c.Children)           // One parent has many children
            .HasForeignKey(c => c.ParentCommentId)
            .OnDelete(DeleteBehavior.Restrict);  // WARNING: Don't use Cascade here!

        // Why Restrict and not Cascade?
        // With Cascade, deleting a parent would automatically delete ALL children,
        // grandchildren, etc. This can be:
        // 1. Unexpected behaviour for users
        // 2. A database performance issue (many deletes)
        // 3. A data integrity risk (accidental mass deletion)
        // Better to handle subtree deletion explicitly in application code

        // ========== INDEXES: Critical for performance ==========

        // Index on ParentCommentId - used when loading children
        // "SELECT * FROM comments WHERE parent_comment_id = @id"
        builder.HasIndex(c => c.ParentCommentId);

        // Index on PostId - used when loading all comments for a post
        // "SELECT * FROM comments WHERE post_id = @id"
        builder.HasIndex(c => c.PostId);

        // Composite index for the most common query:
        // "Get all comments for a post, ordered by creation date"
        builder.HasIndex(c => new { c.PostId, c.CreatedAt });
    }
}

डाटाबेस स्कीमा

परिणामित स्कीमा न्यूनतम है - सिर्फ एक स्वयं का ही विदेशी कुंजी:

erDiagram
    COMMENT {
        int id PK
        string content
        string author
        datetime created_at
        int post_id FK
        int parent_comment_id FK "nullable - NULL for root comments"
    }

    BLOG_POST {
        int id PK
        string title
        string content
    }

    BLOG_POST ||--o{ COMMENT : "has"
    COMMENT ||--o{ COMMENT : "has children"

संचालन

नया टिप्पणी प्रविष्ट करें

प्रविष्ट करता है कि यहाँ सुंदर सरल - साथ साथ दिए गए अनुप्रयोग पैटर्न को वास्तव में चमकाते हैं:

public async Task<Comment> AddCommentAsync(
    int postId,
    int? parentId,      // NULL for root comment, parent's ID for a reply
    string author,
    string content,
    CancellationToken ct = default)
{
    // Creating a comment is just setting the parent reference
    // No need to update closure tables, recalculate paths, or renumber anything
    var comment = new Comment
    {
        PostId = postId,
        ParentCommentId = parentId,  // This single reference defines the hierarchy
        Author = author,
        Content = content,
        CreatedAt = DateTime.UtcNow
    };

    context.Comments.Add(comment);
    await context.SaveChangesAsync(ct);

    logger.LogInformation("Added comment {CommentId} to post {PostId}", comment.Id, postId);
    return comment;
}

बच्चों की परवरिश कीजिए

एकल सूचीबद्ध क्वेरी - तेज तथा सरल:

public async Task<List<Comment>> GetChildrenAsync(int commentId, CancellationToken ct = default)
{
    // This is WHERE adjacency lists shine - getting children is trivial
    // Single indexed lookup: WHERE parent_comment_id = @id
    return await context.Comments
        .AsNoTracking()                              // Read-only, no tracking overhead
        .Where(c => c.ParentCommentId == commentId)  // Uses the index we defined
        .OrderBy(c => c.CreatedAt)                   // Chronological order
        .ToListAsync(ct);
}

तैनाती प्राप्त करें ( हार्ड पार्ट)

यहाँ है जहां सहवास सूची उनकी कमज़ोरी को प्रदर्शित करती है. एक बार फिर, आपको बहुत सारे दौरों के बिना करना होगा: माता पिता, पिता के माता पिता पाने, दादा... और फिर भी.

शुक्र है, एसक्यूएल का रिकर्सिव सीटीईएस बचाव के लिए आते हैं:

public async Task<List<Comment>> GetAncestorsAsync(int commentId, CancellationToken ct = default)
{
    // WHY RAW SQL?
    // EF Core doesn't have great support for recursive CTEs
    // We need to drop down to raw SQL for this

    // HOW THE CTE WORKS:
    // 1. Start with the target comment (WHERE id = {0})
    // 2. UNION ALL joins each result with its parent (JOIN on parent_comment_id)
    // 3. PostgreSQL keeps doing this until no more parents are found
    // 4. We exclude the starting comment (WHERE id != {0}) to get only ancestors

    var sql = @"
        WITH RECURSIVE ancestors AS (
            -- Base case: start with our target comment
            SELECT * FROM comments WHERE id = {0}

            UNION ALL

            -- Recursive case: join each result with its parent
            SELECT c.*
            FROM comments c
            INNER JOIN ancestors a ON c.id = a.parent_comment_id
        )
        -- Return all ancestors except the starting comment, in ID order (root first)
        SELECT * FROM ancestors WHERE id != {0}
        ORDER BY id";

    return await context.Comments
        .FromSqlRaw(sql, commentId)
        .AsNoTracking()
        .ToListAsync(ct);
}

गहराई के साथ संपूर्ण उपतरू प्राप्त करें

साथ ही एक पुनरावर्ती CTE की जरूरत है, लेकिन इस बार हम जाने के रूप में गहराई ट्रैक करते हैं:

public async Task<List<CommentWithDepth>> GetDescendantsWithDepthAsync(
    int commentId,
    CancellationToken ct = default)
{
    // Similar to ancestors, but we go DOWN the tree instead of UP
    // We also track depth so we know how to indent in the UI

    var sql = @"
        WITH RECURSIVE descendants AS (
            -- Base case: start with our target comment at depth 0
            SELECT *, 0 as depth FROM comments WHERE id = {0}

            UNION ALL

            -- Recursive case: find children of each result, incrementing depth
            SELECT c.*, d.depth + 1
            FROM comments c
            INNER JOIN descendants d ON c.parent_comment_id = d.id
        )
        -- Return all descendants, ordered for display
        -- depth first, then by creation time within each level
        SELECT id, content, author, created_at, post_id, parent_comment_id, depth
        FROM descendants
        WHERE id != {0}
        ORDER BY depth, created_at";

    // Note: We need a special DTO to capture the depth column
    // EF Core's FromSqlRaw won't automatically map extra columns to entity properties
    return await context.Database
        .SqlQueryRaw<CommentWithDepth>(sql, commentId)
        .ToListAsync(ct);
}

// DTO to hold comment data plus computed depth
public class CommentWithDepth
{
    public int Id { get; set; }
    public string Content { get; set; } = string.Empty;
    public string Author { get; set; } = string.Empty;
    public DateTime CreatedAt { get; set; }
    public int PostId { get; set; }
    public int? ParentCommentId { get; set; }
    public int Depth { get; set; }  // Computed by the CTE
}

यूआई के लिए नेस्टेंट ट्री स्ट्रक्चर बनाना

अक्सर क्या आप वास्तव में एक पेड़ संरचना है, एक फ्लैट सूची नहीं है. यहाँ कैसे एक तेजी से निर्माण करने के लिए है:

public async Task<List<CommentTreeNode>> GetCommentTreeAsync(int postId, CancellationToken ct = default)
{
    // STRATEGY:
    // 1. Load ALL comments for the post in a single query (fast, one round trip)
    // 2. Build the tree structure in memory (also fast, just pointer manipulation)

    // Step 1: Get all comments for this post
    var allComments = await context.Comments
        .AsNoTracking()
        .Where(c => c.PostId == postId)
        .OrderBy(c => c.CreatedAt)  // Consistent ordering
        .ToListAsync(ct);

    // Step 2: Create a lookup by parent ID
    // This gives us O(1) access to children of any comment
    var lookup = allComments.ToLookup(c => c.ParentCommentId);

    // Step 3: Build the tree starting from root comments (ParentCommentId = null)
    return BuildTree(lookup, null);
}

private List<CommentTreeNode> BuildTree(
    ILookup<int?, Comment> lookup,
    int? parentId)
{
    // Recursively build tree nodes
    // lookup[parentId] gives us all comments whose parent is 'parentId'
    return lookup[parentId]
        .Select(c => new CommentTreeNode
        {
            Comment = c,
            Children = BuildTree(lookup, c.Id)  // Recurse to get children
        })
        .ToList();
}

public class CommentTreeNode
{
    public Comment Comment { get; set; } = null!;
    public List<CommentTreeNode> Children { get; set; } = new();

    // Convenience property for UI
    public bool HasChildren => Children.Count > 0;
}

उपतरू मिटाएँ

मिटाने के लिए पहले सभी बच्चों को पाना ज़रूरी है:

public async Task DeleteSubtreeAsync(int commentId, CancellationToken ct = default)
{
    // We need to find and delete all descendants, then the comment itself
    // Using a CTE to get all IDs, then bulk delete

    var sql = @"
        WITH RECURSIVE subtree AS (
            SELECT id FROM comments WHERE id = {0}
            UNION ALL
            SELECT c.id FROM comments c
            INNER JOIN subtree s ON c.parent_comment_id = s.id
        )
        DELETE FROM comments WHERE id IN (SELECT id FROM subtree)";

    var deleted = await context.Database.ExecuteSqlRawAsync(sql, new object[] { commentId }, ct);

    logger.LogInformation("Deleted {Count} comments in subtree rooted at {CommentId}",
        deleted, commentId);
}

उपतरू खिसकाएँ

यह वह जगह है जहाँ मेल - मिलाप की सूची वास्तव में तेज़ चमक रही है:

public async Task MoveSubtreeAsync(
    int commentId,
    int newParentId,
    CancellationToken ct = default)
{
    // In adjacency list, moving a subtree is just updating ONE row!
    // All descendants automatically move with their parent because
    // their ParentCommentId still points to their direct parent

    var comment = await context.Comments.FindAsync(new object[] { commentId }, ct);
    if (comment == null)
    {
        throw new InvalidOperationException($"Comment {commentId} not found");
    }

    // Prevent creating a cycle (moving a node under its own descendant)
    // This would create an infinite loop in our tree
    var ancestors = await GetAncestorsAsync(newParentId, ct);
    if (ancestors.Any(a => a.Id == commentId))
    {
        throw new InvalidOperationException("Cannot move a comment under its own descendant");
    }

    comment.ParentCommentId = newParentId;
    await context.SaveChangesAsync(ct);

    logger.LogInformation("Moved comment {CommentId} to new parent {NewParentId}",
        commentId, newParentId);
}

प्रवाहित दृश्य अनुमोदन क्वैरी करें

sequenceDiagram
    participant App as Application
    participant EF as EF Core
    participant DB as PostgreSQL

    Note over App,DB: Getting Children (Simple - O(1))
    App->>EF: GetChildrenAsync(commentId)
    EF->>DB: SELECT * FROM comments WHERE parent_id = @id
    DB-->>EF: Results (indexed lookup)
    EF-->>App: List<Comment>

    Note over App,DB: Getting Ancestors (Recursive - O(d) where d=depth)
    App->>EF: GetAncestorsAsync(commentId)
    EF->>DB: WITH RECURSIVE ancestors AS (...)
    DB->>DB: Traverse parent_id chain recursively
    DB-->>EF: All ancestors
    EF-->>App: List<Comment>

परफ़ॉर्मेंस कैरेक्टर्स

IMTRENT ऑपरेशन GNOME जटिलता डाटाबेस राउंडर नोट्स |-----------|------------|---------------------|-------| IMTICONICO( 1) बड़ी मात्रा में सिर्फ अभिभावक सेट कर दिया गया हैComment IMTANOO( 1) 124 इंडेक्सिंग देखने योग्य बच्चों को मिलता है IMTE( DE) DTH( DTE) DT = गहराई के साथ, DTCEL में काम करता है IMTINTHO( n) DTE के साथ 1 ("TE) n = उप- BOSON आकार ol IMTINTHOOLICOOL बस एक पंक्ति का अद्यतन करता है IMDINTHO( n) DTE के साथ ("TE) n = उप- rowz आकार को मिटाएँ

प्रोक्शन्स और कॉनस्ट्स

आपसी रिश्‍तों में दरार |------|------| उम्मीद है कि एक बार जब हम किसी चीज़ को समझने और लागू करने के लिए ज़रूरी है कि हम पहले से ही हल कर लें, तब हम क्या कर सकते हैं? SECTCT CTCACT को बहुत गहरे पेड़ों पर धीमा किया जा सकता है शुतुरमुर्ग एक छोटी - सी चाल है (जिसे एक पंक्ति की इजाज़त दी गयी है) मगर बिना गहराई तक गहराई तक पहुँचने का कोई आसान रास्ता नहीं स्वाभाविक रूप से स्वाभाविक रूप से शिशुओं को लोड करने के बिना स्वाभाविक रूप से गिन नहीं सकता D+1 समस्याओं को अनदेखा करने के लिए कोई डेटा लालता नहीं

एएसजाता सूची का उपयोग करने के लिए जब

एडज़ीसी सूची चुनें जब:

  • आपका पदक्रम कम है (5- 6 स्तर से कम)
  • आप बार- बार सब खजूरों को खिसकाते हैं
  • आप ईएफ कोर के नेविगेशन गुण स्वाभाविक रूप से कार्य करने के लिए चाहते हैं
  • सरल आवश्यकताएँ जहाँ बारंबारता स्वीकार्य हैं
  • प्रदर्शन प्रदर्शन से ज्यादा ज़रूरी है

जब गलत काम करने की सूची दी जाए, तब धर्मशास्त्रीय सूची से दूर रहें:

  • आपके पास गहरे अंक हैं (१०+ स्तर)
  • आप अकसर "सभी संतति" या "सभी पूर्वज" क्वैरी करते हैं
  • पढ़ने का प्रदर्शन गंभीर है
  • आप उन्हें लोड किए बिना बच्चों की गिनती करने की जरूरत है

श्रेणी नेविगेशन

Finding related posts...
logo

© 2026 Scott Galloway — Unlicense — All content and source code on this site is free to use, copy, modify, and sell.