# आधुनिक सीक्यूस और घटनाएँ

<!--category-- ASP.NET, Architecture, CQRS, Event Sourcing -->
<datetime class="hidden">2025-01-13T12:00</datetime>

> **ग़ौर करें**: यह एक पुराना लेख है जिसे मैं छोड़ना भूल गया ।

यहाँ है, आनंद!

मैं इसे अद्यतन किया लेकिन मैं याद किया हो सकता है कुछ मुद्दों हो सकता है.

## QRS और घटना, दोनों पैटर्नों का ज़िक्र अकसर एक - साथ किया जाता है, लेकिन अकसर उन्हें गलत समझा जाता है ।

इस लेख में, मैं आपको दिखाने के लिए जा रहा हूँ उन्हें आधुनिक औज़ारों का उपयोग करने के लिए ठीक तरह से काम करने के लिए।

- **मैं भी तुम को "समसीय-संत्र" कैश- आधारित विकल्प दिखाता हूँ, और समझाता हूँ कि क्यों मैनुअल कैश के साथ घटना को मिलाने की कोशिश कर रहा है।**परिचय
- **CQRS (अंग्रेजी ज़िम्मेदारी की घोषणा) और घटना दोनों ही विशिष्ट रूप हैं जो असाधारण रूप से एक साथ काम करते हैं:**सीक्यूआरएस

- अपने लेखन मॉडल से अपने पढ़ने के मॉडल अलग करना

- घटना अत्यन्त तेज हो रही है
- - हर स्थिति परिवर्तन को घटना के एक अवैध अनुक्रम के रूप में भंडारित कर रहा है
- जब मार्टेन की तरह उपकरण के साथ ठीक से किया, आप पाते हैं:
- प्रत्येक परिवर्तन का गलत निशान पूरा करें

समय में किसी भी बिन्दु पर राज्य फिर से बनाने के लिए शक्‍ति**मॉडल सहायकों को स्वचलित पढ़ा जा रहा है**डोमेन का डिजाइन के साथ स्वाभाविक फिट

[TOC]

## इस लेख में हम देखेंगे कि हम ऐसा कैसे कर सकते हैं

ठीक

```csharp
// Write Model - Commands that change state
public record CreateBlogPostCommand(string Title, string Content, string AuthorId);

// Read Model - DTOs optimised for display
public class BlogPostListItemDto
{
    public Guid Id { get; set; }
    public string Title { get; set; }
    public string AuthorName { get; set; }
    public DateTime PublishedDate { get; set; }
    public int CommentCount { get; set; }
}
```



## यदि आप जल्दी से और scci-by कैश पर आधारित प्रवेश करना चाहते हैं, तो मैं कि अंत पर संक्षिप्त रूप से कवर होगा - लेकिन यह वास्तव में सीQRS नहीं है, और यह आपको घटना SQRS के लाभ नहीं देता है।

सीक्यूआर क्या है?

```csharp
// Traditional: Store current state
public class BlogPost
{
    public Guid Id { get; set; }
    public string Title { get; set; }  // Current title
    public bool IsPublished { get; set; }  // Current status
}

// Event Sourcing: Store the events
public record BlogPostCreated(Guid Id, string Title, string Content, DateTime CreatedAt);
public record BlogPostTitleChanged(Guid Id, string OldTitle, string NewTitle, DateTime ChangedAt);
public record BlogPostPublished(Guid Id, DateTime PublishedAt);
```

अपने कोर पर, सीक्यूआरएस का अर्थ है पढ़ने और डाटा लिखने के लिए अलग मॉडल का प्रयोग करें:

## लेखन पक्ष व्यापार तर्क और वैधता पर ध्यान केंद्रित करता है.

**पढ़ने का किनारा प्रदर्शन के लिए सामान्य तथा अधिकतम है.**सरल पर्याप्त है, लेकिन सही सीक्यूएस का अर्थ है वे अपने अनुप्रयोग के माध्यम से पूरी तरह से अलग पथ कर रहे हैं.

**घटना क्या है?**मौजूदा स्थिति को स्टोर करने के बजाय, आप उन घटनाओं को जमा करते हैं जो कि राज्य के अधीन हो गए हैं:

**वर्तमान स्थिति को पुनःप्ले करने वाली घटना द्वारा लिया गया है.**यह आप अपने तंत्र में कभी हुआ है कि सब कुछ का पूरा इतिहास देता है.

**क्यों घटना का इस्तेमाल सीक्यूस के साथ करें?**ऑडियोपथ ट्रैल पूरा करें

**: हर बदलाव का रिकॉर्ड है ।**आर्थिक व्यवस्थाओं, स्वास्थ्य देखभाल, या आप जहाँ भी हो, यह साबित करने की ज़रूरत है कि क्या हुआ और कब हुआ ।

### टेंपोरल क्वाटरर्स

**: "इस ब्लॉग पोस्ट ने पिछले मंगलवार की तरह क्या देखा?" संक्षिप्त रूप में फिर से उस बिंदु पर घटनाओं को फिर से लोड किया.**डिबगिंग

**: उन घटनाओं के आधार पर फिर से कोशिश करके बग जोड़े.**व्यापार अधिकार

**: बिना पायलटों के ऐतिहासिक आंकड़ों से नई रिपोर्टें बनाइए ।**घटनाएँ पहले से ही मौजूद हैं.

**स्वाभाविक सीआरआरटीएस अनुरूप**: घटनाएँ स्वाभाविक रूप से अलग होती हैं (कंत्रित घटनाएँ) जिन्हें पढ़ने से अलग किया गया है ।

## जब आप नहीं करना चाहिए

सादा स्लोरो[: अगर आप सिर्फ डेटा जमा कर रहे हैं और फिर से प्राप्त कर रहे हैं, तो घटना अपिंग हास्यास्पद है.](https://martendb.io/)अनुभव के बिना छोटा टीम

: सीखने का वक्र खड़ी है.

- डी- बस आवश्यकताएँ ही नहीं
- : अगर आप केवल मौजूदा स्थिति के बारे में परवाह करते हैं, तो इतिहास भंडारित नहीं है.
- बड़ा द्विचर डाटा
- : घटनाएँ छवियों, वीडियो, फ़ाइलें के साथ खराब होती हैं.
- आधुनिक घटना .EENT: मारटन

### घटना के लिए सबसे अच्छा औज़ार 2025 में है

मारटेन

```bash
dotnet add package Marten
dotnet add package Marten.AspNetCore
```

`Program.cs`:

```csharp
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddMarten(options =>
{
    options.Connection(builder.Configuration.GetConnectionString("Marten")!);

    // Register event types
    options.Events.AddEventType<BlogPostCreated>();
    options.Events.AddEventType<BlogPostPublished>();
    options.Events.AddEventType<BlogPostTitleChanged>();
    options.Events.AddEventType<CommentAdded>();

    // Configure async projections
    options.Projections.Add<BlogPostProjection>(ProjectionLifecycle.Async);
});

builder.Services.AddMediatR(cfg =>
    cfg.RegisterServicesFromAssembly(typeof(Program).Assembly));

var app = builder.Build();
```

### यह Meliz Mela Meli M द्वारा सक्रिय रूप से बनाया गया एक घटना है, और यह सिर्फ काम करता है.

मार्टन क्यों?

```mermaid
flowchart TB
    subgraph Client["Client Application"]
        UI[User Interface]
    end

    subgraph Commands["Command Side (Writes)"]
        CMD[Commands] --> CMDH[Command Handlers]
        CMDH --> MARTEN[Marten Session]
        MARTEN --> EVENTS[(Event Store)]
    end

    subgraph Background["Async Processing"]
        EVENTS -.->|Event Stream| DAEMON[Marten Async Daemon]
        DAEMON --> PROJ[Projections]
        PROJ --> READDB[(Read Models)]
    end

    subgraph Queries["Query Side (Reads)"]
        QRY[Queries] --> QRYH[Query Handlers with Dapper]
        QRYH --> READDB
    end

    UI -->|Commands| CMD
    UI -->|Queries| QRY

    classDef commandStyle fill:none,stroke:#e63946,stroke-width:3px
    classDef queryStyle fill:none,stroke:#457b9d,stroke-width:3px
    classDef dataStyle fill:none,stroke:#2a9d8f,stroke-width:3px

    class CMD,CMDH,MARTEN commandStyle
    class QRY,QRYH queryStyle
    class EVENTS,READDB dataStyle
```

एसक्यूएल पर अंतर्निर्मित (आप पहले से ही जानते हैं)

- **मॉडल पढ़ने के लिए घटनाओं से स्वचलित प्रोजेक्शन्स**प्रोजेक्शन प्रक्रिया के लिए एएसएसई डेमनName
- **समृद्ध क्वेरी क्षमता**उत्पाद तैयार और लड़ाई की जांच
- **मार्च्टेटन सेट किया जा रहा है**पैकेज संस्थापित करें:
- कॉन्फ़िगर

## यु. पू.

यहाँ सब कुछ एक साथ फिट होता है:

```csharp
// Always past tense - these things have happened
public record BlogPostCreated(
    Guid BlogPostId,
    string Title,
    string Content,
    string AuthorId,
    DateTime CreatedAt
);

public record BlogPostPublished(
    Guid BlogPostId,
    DateTime PublishedAt
);

public record BlogPostTitleChanged(
    Guid BlogPostId,
    string OldTitle,
    string NewTitle,
    DateTime ChangedAt
);

public record CommentAdded(
    Guid BlogPostId,
    Guid CommentId,
    string Author,
    string Content,
    DateTime CreatedAt
);
```

कुंजी पाइंट्स:

- **कमांड्स**घटनाओं को स्टोर करने के लिए जोड़ें
- **एसएसएसाई डेमन**प्रक्रिया घटनाएँ तथा अपडेट मॉडल पढ़ सकते हैं
- **क्वार्टर**आम पढ़े जाने वाले मॉडलों से पढ़ा जा सकता है

## कोई हस्तचालित कैश अवैध जाँच की आवश्यकता नहीं!

घटनाएँ नियत की जा रही हैं

```csharp
public class BlogPost
{
    // Marten requires an Id property
    public Guid Id { get; set; }

    // Current state (private setters)
    public string Title { get; private set; } = string.Empty;
    public string Content { get; private set; } = string.Empty;
    public string AuthorId { get; private set; } = string.Empty;
    public bool IsPublished { get; private set; }
    public DateTime? PublishedDate { get; private set; }
    private readonly List<Comment> _comments = new();
    public IReadOnlyList<Comment> Comments => _comments.AsReadOnly();

    // Apply methods - called by Marten when replaying events
    public void Apply(BlogPostCreated e)
    {
        Id = e.BlogPostId;
        Title = e.Title;
        Content = e.Content;
        AuthorId = e.AuthorId;
    }

    public void Apply(BlogPostPublished e)
    {
        IsPublished = true;
        PublishedDate = e.PublishedAt;
    }

    public void Apply(BlogPostTitleChanged e)
    {
        Title = e.NewTitle;
    }

    public void Apply(CommentAdded e)
    {
        _comments.Add(new Comment
        {
            Id = e.CommentId,
            Author = e.Author,
            Content = e.Content,
            CreatedAt = e.CreatedAt
        });
    }

    // Business logic methods that produce events
    public static BlogPostCreated Create(string title, string content, string authorId)
    {
        if (string.IsNullOrWhiteSpace(title))
            throw new ArgumentException("Title is required");

        return new BlogPostCreated(
            Guid.NewGuid(),
            title,
            content,
            authorId,
            DateTime.UtcNow
        );
    }

    public BlogPostPublished Publish()
    {
        if (IsPublished)
            throw new InvalidOperationException("Post is already published");

        return new BlogPostPublished(Id, DateTime.UtcNow);
    }

    public BlogPostTitleChanged ChangeTitle(string newTitle)
    {
        if (string.IsNullOrWhiteSpace(newTitle))
            throw new ArgumentException("Title cannot be empty");

        if (newTitle == Title)
            throw new InvalidOperationException("New title is the same as current title");

        return new BlogPostTitleChanged(Id, Title, newTitle, DateTime.UtcNow);
    }
}

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

घटनाएँ सक्षम नहीं की गई हैं जो उन चीजों का वर्णन करती हैं जो हुई हैं:

1. घटनाएँ होनी चाहिए:
2. म्यूटेबल
3. - एक बार लिखा गया, कभी नहीं बदला

## पिछला काल

- वे वर्णन क्या हुआ

```csharp
// Define commands
public record CreateBlogPostCommand(
    string Title,
    string Content,
    string AuthorId
) : IRequest<Guid>;

public record PublishBlogPostCommand(Guid BlogPostId) : IRequest;

public record ChangeBlogPostTitleCommand(
    Guid BlogPostId,
    string NewTitle
) : IRequest;

// Handler for creating a blog post
public class CreateBlogPostHandler : IRequestHandler<CreateBlogPostCommand, Guid>
{
    private readonly IDocumentSession _session;

    public CreateBlogPostHandler(IDocumentSession session)
    {
        _session = session;
    }

    public async Task<Guid> Handle(CreateBlogPostCommand request, CancellationToken cancellationToken)
    {
        // Create the event
        var created = BlogPost.Create(
            request.Title,
            request.Content,
            request.AuthorId
        );

        // Start a new event stream
        _session.Events.StartStream<BlogPost>(created.BlogPostId, created);

        await _session.SaveChangesAsync(cancellationToken);

        return created.BlogPostId;
    }
}

// Handler for publishing
public class PublishBlogPostHandler : IRequestHandler<PublishBlogPostCommand>
{
    private readonly IDocumentSession _session;

    public PublishBlogPostHandler(IDocumentSession session)
    {
        _session = session;
    }

    public async Task Handle(PublishBlogPostCommand request, CancellationToken cancellationToken)
    {
        // Load the aggregate by replaying its events
        var blogPost = await _session.Events.AggregateStreamAsync<BlogPost>(
            request.BlogPostId,
            token: cancellationToken
        );

        if (blogPost == null)
            throw new InvalidOperationException($"Blog post {request.BlogPostId} not found");

        // Business logic produces new event
        var published = blogPost.Publish();

        // Append event to the stream
        _session.Events.Append(request.BlogPostId, published);

        await _session.SaveChangesAsync(cancellationToken);
    }
}

// Handler for changing title
public class ChangeBlogPostTitleHandler : IRequestHandler<ChangeBlogPostTitleCommand>
{
    private readonly IDocumentSession _session;

    public ChangeBlogPostTitleHandler(IDocumentSession session)
    {
        _session = session;
    }

    public async Task Handle(ChangeBlogPostTitleCommand request, CancellationToken cancellationToken)
    {
        var blogPost = await _session.Events.AggregateStreamAsync<BlogPost>(
            request.BlogPostId,
            token: cancellationToken
        );

        if (blogPost == null)
            throw new InvalidOperationException($"Blog post {request.BlogPostId} not found");

        var titleChanged = blogPost.ChangeTitle(request.NewTitle);

        _session.Events.Append(request.BlogPostId, titleChanged);

        await _session.SaveChangesAsync(cancellationToken);
    }
}
```

व्यवसाय में धनी

1. - "Brigigide" नहीं "प्रयोगी अद्यतन"
2. वी. कार्ड तैयार किया जा रहा है
3. द्वार लिखने का मॉडल हैं.
4. वे व्यापार नियम वैध हैं और घटनाओं को उत्पन्‍न करते हैं:

पैटर्न:

## व्यापार पद्धति वैध हैं तथा वापसी घटनाएँ

आंतरिक स्थिति अद्यतन करने के लिए विधियाँ लागू करें

```csharp
// Read model - optimised for queries
public class BlogPostReadModel
{
    public Guid Id { get; set; }
    public string Title { get; set; } = string.Empty;
    public string Content { get; set; } = string.Empty;
    public string AuthorId { get; set; } = string.Empty;
    public DateTime CreatedAt { get; set; }
    public DateTime? PublishedAt { get; set; }
    public bool IsPublished { get; set; }
    public int CommentCount { get; set; }
}

// Projection - tells Marten how to build read models from events
public class BlogPostProjection : MultiStreamProjection<BlogPostReadModel, Guid>
{
    public BlogPostProjection()
    {
        // Identity tells Marten which stream each event belongs to
        Identity<BlogPostCreated>(x => x.BlogPostId);
        Identity<BlogPostPublished>(x => x.BlogPostId);
        Identity<BlogPostTitleChanged>(x => x.BlogPostId);
        Identity<CommentAdded>(x => x.BlogPostId);
    }

    // Apply methods - Marten calls these to update read models
    public void Apply(BlogPostReadModel view, BlogPostCreated e)
    {
        view.Id = e.BlogPostId;
        view.Title = e.Title;
        view.Content = e.Content;
        view.AuthorId = e.AuthorId;
        view.CreatedAt = e.CreatedAt;
        view.IsPublished = false;
    }

    public void Apply(BlogPostReadModel view, BlogPostPublished e)
    {
        view.IsPublished = true;
        view.PublishedAt = e.PublishedAt;
    }

    public void Apply(BlogPostReadModel view, BlogPostTitleChanged e)
    {
        view.Title = e.NewTitle;
    }

    public void Apply(BlogPostReadModel view, CommentAdded e)
    {
        view.CommentCount++;
    }
}
```

मारटन घटना लगन और फिर खेल को संभालता है

## कमांड हैंडलर्स (Wigig)

कमांडों को नदियों में जोड़ने के लिए हैंडल किया जाता है:

```csharp
// Define queries
public record GetRecentBlogPostsQuery(
    int Count,
    bool PublishedOnly
) : IRequest<List<BlogPostListItemDto>>;

public record GetBlogPostByIdQuery(Guid Id) : IRequest<BlogPostDetailDto?>;

// DTOs for display
public class BlogPostListItemDto
{
    public Guid Id { get; set; }
    public string Title { get; set; } = string.Empty;
    public string AuthorName { get; set; } = string.Empty;
    public DateTime CreatedAt { get; set; }
    public DateTime? PublishedAt { get; set; }
    public int CommentCount { get; set; }
    public bool IsPublished { get; set; }
}

public class BlogPostDetailDto
{
    public Guid Id { get; set; }
    public string Title { get; set; } = string.Empty;
    public string Content { get; set; } = string.Empty;
    public string AuthorId { get; set; } = string.Empty;
    public string AuthorName { get; set; } = string.Empty;
    public DateTime CreatedAt { get; set; }
    public DateTime? PublishedAt { get; set; }
    public bool IsPublished { get; set; }
    public List<CommentDto> Comments { get; set; } = new();
}

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

// Query handlers
public class GetRecentBlogPostsHandler : IRequestHandler<GetRecentBlogPostsQuery, List<BlogPostListItemDto>>
{
    private readonly string _connectionString;

    public GetRecentBlogPostsHandler(IConfiguration config)
    {
        _connectionString = config.GetConnectionString("Marten")!;
    }

    public async Task<List<BlogPostListItemDto>> Handle(
        GetRecentBlogPostsQuery request,
        CancellationToken cancellationToken)
    {
        await using var connection = new NpgsqlConnection(_connectionString);

        // Query the Marten-generated read model table
        const string sql = @"
            SELECT
                bp.id AS Id,
                bp.title AS Title,
                u.name AS AuthorName,
                bp.created_at AS CreatedAt,
                bp.published_at AS PublishedAt,
                bp.comment_count AS CommentCount,
                bp.is_published AS IsPublished
            FROM blog_post_read_models bp
            LEFT JOIN users u ON bp.author_id = u.id
            WHERE (@PublishedOnly = false OR bp.is_published = true)
            ORDER BY
                CASE WHEN bp.is_published THEN bp.published_at
                     ELSE bp.created_at
                END DESC
            LIMIT @Count";

        var results = await connection.QueryAsync<BlogPostListItemDto>(
            sql,
            new
            {
                PublishedOnly = request.PublishedOnly,
                Count = request.Count
            });

        return results.ToList();
    }
}

public class GetBlogPostByIdHandler : IRequestHandler<GetBlogPostByIdQuery, BlogPostDetailDto?>
{
    private readonly string _connectionString;

    public GetBlogPostByIdHandler(IConfiguration config)
    {
        _connectionString = config.GetConnectionString("Marten")!;
    }

    public async Task<BlogPostDetailDto?> Handle(
        GetBlogPostByIdQuery request,
        CancellationToken cancellationToken)
    {
        await using var connection = new NpgsqlConnection(_connectionString);

        const string sql = @"
            SELECT
                bp.id AS Id,
                bp.title AS Title,
                bp.content AS Content,
                bp.author_id AS AuthorId,
                u.name AS AuthorName,
                bp.created_at AS CreatedAt,
                bp.published_at AS PublishedAt,
                bp.is_published AS IsPublished
            FROM blog_post_read_models bp
            LEFT JOIN users u ON bp.author_id = u.id
            WHERE bp.id = @Id";

        var post = await connection.QuerySingleOrDefaultAsync<BlogPostDetailDto>(
            sql,
            new { request.Id });

        if (post == null)
            return null;

        // Get comments from event stream if needed
        // Or maintain a separate comment read model

        return post;
    }
}
```

प्रवाहः

## घटना फिर से लोड करें (या नया बनाएँ)

काल व्यापार विधि (vervs और घटना को लौटाता है)

```csharp
[ApiController]
[Route("api/[controller]")]
public class BlogPostsController : ControllerBase
{
    private readonly IMediator _mediator;

    public BlogPostsController(IMediator mediator)
    {
        _mediator = mediator;
    }

    [HttpGet]
    public async Task<ActionResult<List<BlogPostListItemDto>>> GetRecent(
        [FromQuery] int count = 10,
        [FromQuery] bool publishedOnly = true)
    {
        var query = new GetRecentBlogPostsQuery(count, publishedOnly);
        var results = await _mediator.Send(query);
        return Ok(results);
    }

    [HttpGet("{id}")]
    public async Task<ActionResult<BlogPostDetailDto>> GetById(Guid id)
    {
        var query = new GetBlogPostByIdQuery(id);
        var result = await _mediator.Send(query);

        if (result == null)
            return NotFound();

        return Ok(result);
    }

    [HttpPost]
    public async Task<ActionResult<Guid>> Create([FromBody] CreateBlogPostCommand command)
    {
        var postId = await _mediator.Send(command);
        return CreatedAtAction(nameof(GetById), new { id = postId }, postId);
    }

    [HttpPost("{id}/publish")]
    public async Task<ActionResult> Publish(Guid id)
    {
        await _mediator.Send(new PublishBlogPostCommand(id));
        return NoContent();
    }

    [HttpPut("{id}/title")]
    public async Task<ActionResult> ChangeTitle(
        Guid id,
        [FromBody] ChangeBlogPostTitleCommand command)
    {
        if (id != command.BlogPostId)
            return BadRequest();

        await _mediator.Send(command);
        return NoContent();
    }
}
```

## आगे बढ़ने के लिए एक कार्यक्रम जोड़ें

परिवर्तन सहेजें

```mermaid
sequenceDiagram
    participant Client
    participant Controller
    participant MediatR
    participant CommandHandler
    participant Marten
    participant EventStore
    participant AsyncDaemon
    participant ReadDB
    participant QueryHandler

    Note over Client,ReadDB: Write Operation
    Client->>Controller: POST /api/blogposts
    Controller->>MediatR: Send CreateBlogPostCommand
    MediatR->>CommandHandler: Handle command
    CommandHandler->>CommandHandler: Validate & create event
    CommandHandler->>Marten: StartStream(event)
    Marten->>EventStore: Append event
    EventStore-->>Marten: Success
    Marten-->>CommandHandler: Success
    CommandHandler-->>Controller: Return ID
    Controller-->>Client: 201 Created

    Note over AsyncDaemon,ReadDB: Background Processing
    EventStore->>AsyncDaemon: New event available
    AsyncDaemon->>AsyncDaemon: Apply projection
    AsyncDaemon->>ReadDB: Update read model
    ReadDB-->>AsyncDaemon: Updated

    Note over Client,ReadDB: Read Operation
    Client->>Controller: GET /api/blogposts
    Controller->>MediatR: Send Query
    MediatR->>QueryHandler: Handle query
    QueryHandler->>ReadDB: SELECT with Dapper
    ReadDB-->>QueryHandler: Return data
    QueryHandler-->>Controller: Return DTOs
    Controller-->>Client: 200 OK
```

## मारटन बाकी घटनाओं को जमा करता है, जो कि प्रक्षेपण, आदि.

मॉडलों और परियोजनाओं को पढ़ें

परियोजना परिवर्तन घटनाएँ सामान्य रूप से पढ़ने योग्य मॉडलों में बदल जाते हैं:

```csharp
builder.Services.AddMarten(options =>
{
    // This projection runs synchronously
    options.Projections.Add<CriticalDataProjection>(ProjectionLifecycle.Inline);

    // This projection runs async
    options.Projections.Add<BlogPostProjection>(ProjectionLifecycle.Async);
});
```

मार्टेन के अतुल्यकालिक डेमन घटनाएँ पृष्ठभूमि में होती हैं और तिथि पर मॉडल पढ़ने की जारी रहती हैं.

```csharp
var blogPost = await _session.Events.AggregateStreamAsync<BlogPost>(id);
```

## आप कोई कैश अवैध कोड लिख नहीं है - यह स्वचालित है.

Dapper के साथ क्वैरी बाजू

### अब हम अधिकतम प्रदर्शन के लिए डीप्पर का उपयोग कर पढ़ने के मॉडलों को क्वैरी करते हैं:

- कोई कंचा कोड नहीं.
- कोई अवैध तर्क नहीं.
- मार्टेन सिंक में पढ़े मॉडलों को स्वचालित रखता है.
- नियंत्रक

मीडिया पर, नियंत्रण बहुत ही सरल है:

### पूर्ण प्रवाह

```csharp
// Command handler
public class CreateBlogPostHandler : IRequestHandler<CreateBlogPostCommand, int>
{
    private readonly ApplicationDbContext _context;
    private readonly IMemoryCache _cache;

    public async Task<int> Handle(CreateBlogPostCommand request, CancellationToken cancellationToken)
    {
        var blogPost = new BlogPost
        {
            Title = request.Title,
            Content = request.Content,
            AuthorId = request.AuthorId,
            PublishedDate = DateTime.UtcNow
        };

        _context.BlogPosts.Add(blogPost);
        await _context.SaveChangesAsync(cancellationToken);

        // Manual cache invalidation - this is the tedious bit
        _cache.Remove("recent-posts");
        _cache.Remove($"author-posts-{request.AuthorId}");
        _cache.Remove($"post-{blogPost.Id}");

        return blogPost.Id;
    }
}

// Query handler
public class GetRecentPostsHandler : IRequestHandler<GetRecentPostsQuery, List<BlogPostDto>>
{
    private readonly string _connectionString;
    private readonly IMemoryCache _cache;

    public async Task<List<BlogPostDto>> Handle(GetRecentPostsQuery request, CancellationToken cancellationToken)
    {
        var cacheKey = "recent-posts";

        if (_cache.TryGetValue<List<BlogPostDto>>(cacheKey, out var cached))
            return cached!;

        // Cache miss - query with Dapper
        using var connection = new NpgsqlConnection(_connectionString);
        var posts = (await connection.QueryAsync<BlogPostDto>(
            "SELECT id, title, author_name, published_date FROM blog_posts ORDER BY published_date DESC LIMIT 10"
        )).ToList();

        _cache.Set(cacheKey, posts, TimeSpan.FromMinutes(5));
        return posts;
    }
}
```

### यहाँ यह सब एक साथ काम करता है कैसे है:

- घटना सार्वजनिक रूप से
- एक बात समझने के लिए: अतुल्यकालिक प्रोजेक्शन के साथ, एक घटना लिखने और पढ़ने मॉडल अद्यतन किया जा रहा है के बीच एक छोटा सा अंतराल है.
- आमतौर पर मिली मिली मिली है, लेकिन यह वहाँ है.
- यदि आपको किसी विशिष्ट ऑपरेशन के लिए तत्काल संगतता की आवश्यकता है, तो इनलाइन प्रोजेक्शन्स इस्तेमाल करें:

### या परिस्थितियों को पढ़ने के लिए इस घटना को सीधे ही चेक करें:

**भाग 2: आधा- से- अधिक जानकारी (सी- छाँट)**ठीक है, तो तुमने सही घटना के बारे में पढ़ा है सोचिंग और आप सोच रहे हैं कि "काम का एक बहुत कुछ है."

**बहुत अच्छे।**यहाँ "इनफ़ॉर्मल सीआर" है कि अधिकांश टीम वास्तव में उपयोग करते हैं।

**सेटअप**डाटाबेस में कमांड लिखने के लिए (एएफ या डीएचर के जरिए)

**मैं मेकरीश या आईडीिस्टीश से पढ़ा.**लिखने के बाद इस्तेमाल के लिए औज़ारों को अवैध करता है

**कोई घटना केआईओिंग नहीं, कोई प्रोजेक्शन, कोई अतुल्यकालिक डेमन नहीं**यह सच सीक्यूआरएस नहीं है.

तुम्हें पता नहीं है कि आप एक निष्क्रिय निशान, macuties, या स्वचालित प्रक्षेपण नहीं मिलता है.

## लेकिन आपको कम जटिलता के साथ प्रदर्शन मिलता है ।

क्विक उदाहरण

### जब यह कार्य करता है

जटिल आवश्यकताओं के बगैर सरल अनुप्रयोग

आप प्रदर्शन की जरूरत है लेकिन जटिलता को उचित नहीं कर सकते

### छोटा टीम जो घटना सीखना नहीं चाहती

**कुछ सेकण्डों की स्थिरता स्वीकार्य है**समस्याएँ

**कैश अवैध है**: मिस एक कैश कुंजी और आप केमरिस डाटा सेवा करते हैं.

**हर कमांड को जानना होगा कि कौन सा कैश अवैध है.**सूची पता नहीं लगाएँ (D)

**: आपके पास सिर्फ मौज़ूदा राज्य है.**क्या हुआ या जब साबित नहीं कर सकते.

**यु. पू.**: क्या नहीं पूछ सकता है "दुनिया कल कैसा दिखता है?"

### रेटिंग

: मेपलसीश के साथ, प्रत्येक सर्वर का अपना कैश है.

- सर्वर ए पर अद्यतन, सर्वर बी में अभी भी अनिवार्य डाटा है.
- आईडीकिज़ीश इस को हल करते हैं, लेकिन रेडस जोड़ते हैं.
- वक्रीय
- : कमांडों को कैश कुंजी के साथ जोड़ा जाता है.

क्वैरी बदलें, कमांड तोड़ सकता है.

- यह काम करता है, लेकिन आप खो क्षमता के लिए व्यापार सरल कर रहे हैं.
- कभी कभी कि सही व्यापार-बंद है.
- अक्सर यह नहीं है.

भाग ३: सब से बुरा घटना सोकिंग + मैनुअल कैशिंग

### अब वास्तव में भयानक विचार के लिए: घटनाओं का प्रयोग करते हुए, लेकिन हस्तचालित अवैध कैशों का उपयोग करने की कोशिश भी करते हैं ।

```csharp
// Don't do this!
public class PublishBlogPostHandler : IRequestHandler<PublishBlogPostCommand>
{
    private readonly IDocumentSession _session;
    private readonly IMemoryCache _cache;  // ← BAD

    public async Task Handle(PublishBlogPostCommand request, CancellationToken cancellationToken)
    {
        var blogPost = await _session.Events.AggregateStreamAsync<BlogPost>(request.BlogPostId);
        var published = blogPost.Publish();

        _session.Events.Append(request.BlogPostId, published);
        await _session.SaveChangesAsync(cancellationToken);

        // Manually invalidating cache while using Event Sourcing ← TERRIBLE IDEA
        _cache.Remove($"post-{request.BlogPostId}");
        _cache.Remove("recent-posts");

        // Now you have:
        // 1. Event in event store
        // 2. Cache invalidated
        // 3. But projection hasn't run yet!
        // Queries will hit database before projection completes = stale data
    }
}
```

लोग ऐसा क्यों करते हैं

## वे घटना सोचिंग के निशान और unbulties चाहते हैं, लेकिन वे स्थायी रूप से सुसंगतता के बारे में चिंतित हैं.

तो वे सोचते हैं कि "मैं केवल कैश को अवैध रूप से पढ़ने के लिए सक्षम करता हूँ  और अधिक संगत बनाने के लिए"

### ऐसा मत करो.

**क्यों यह भयानक है**

- आप उद्देश्य पर हार गए हैं
- कार्यक्रम: प्रक्षेपण के माध्यम से पहले ही सोपरिंग मॉडल पढ़ा जा सकता है.
- हस्तचालित कैश जोड़ना का अर्थ है आप उस तंत्र को बाहर कर रहे हैं.
- दोहरा जटिलताएँ

**: अब आपके पास दो सिस्टम हैं सिंक - मारटन प्रक्षेपण में मॉडल पढ़ने के लिए और अपने मैनुअल कैश अवैध.**

- वे संघर्ष करेंगे.
- अस्पस्ट स्थिति
- : मारटेन्स डेमन डेटाबेस अद्यतन करता है.

### आपका कैश अवैधता तत्काल चलाता है.

**वे सिंक से बाहर हैं.**

- कौन - सी बात सही है?
- खोया हुआ लाभ
- घटना सोपरिंग का पूरा बिन्दु है कि प्रक्षेपण घटनाओं से लिया गया है.
- हस्तचालित कैश अवैध है कि मॉडल ब्रेक.

**डिबगिंग सपना**

- : क्या अपेन डाटा क्योंकि प्रक्षेपण नहीं चल रहा है?
- या आप कैश कुंजी को अवैध करना भूल गए?
- या क्योंकि कैश अवैध था लेकिन प्रक्षेपण अभी तक नहीं चला था?

### गुड लक.

**सही सवाल**

- यदि आपको घटना सोज की जरूरत है:

मार्टेन के प्रक्षेपण का प्रयोग करें (अंड या इनलाइन)

पढ़ने के मॉडलों से सीधे क्वैरी करें[समाप्ति संगतता स्वीकारें (यह आमतौर पर ठीक है)](/blog/addingentityframeworkforblogpostspt1)इनलाइन प्रक्षेपण का प्रयोग करें यदि आपको वास्तव में तत्काल संगतता की आवश्यकता है

## अगर आप स्थायी रूप से सुसंगतता को स्वीकार नहीं कर सकते हैं:

- [घटना पुनः प्रयोग न करें](https://martendb.io/)पार्ट 2 से कैश- आधारित समीप का उपयोग करें
- [या सिर्फ EF कोरस के साथ पारंपरिक अपराध का उपयोग करें](https://www.eventstore.com/)दोनों करने की कोशिश मत करो.
- [आप घटना की जटिलता के साथ समाप्त होगा... ... और साथ ही मैनुअल कैश अवैधता.](https://github.com/DapperLib/Dapper)जो करना नहीं है उसकी मिसाल
- [बस मार्टेन के प्रक्षेपण का उपयोग करें.](https://github.com/jbogard/MediatR)वे इस के लिए डिजाइन कर रहे हैं.
- [कंटेनमेंट](https://learn.microsoft.com/en-us/azure/architecture/patterns/cqrs)तीन पास, तीन उदाहरण:
- सही सीक्यूट घटना के साथ (मिरटन)[इस्तेमाल करें जब:](/blog/addingentityframeworkforblogpostspt1)आपको पूरी तरह के निशान की आवश्यकता है