This is a viewer only at the moment see the article on how this works.
To update the preview hit Ctrl-Alt-R (or ⌘-Alt-R on Mac) or Enter to refresh. The Save icon lets you save the markdown file to disk
This is a preview from the server running through my markdig pipeline
Wednesday, 03 December 2025
जब इमारत का निर्माण किया जाता है, तो सबसे महत्वपूर्ण निर्णय आप बनाने के लिए कैसे डेटा पहुँच और वस्तु निर्मित करने के लिए है।
इस विस्तृत दो भाग निर्देशों में, हम सबसे लोकप्रिय डाटा पहुँच पैटर्न का पता लगाने के लिए जा रहे हैं। हम हमारे उदाहरणों में Npegagsl का उपयोग करते हैं (क्योंकि यह ब्लॉग क्या है कि इस ब्लॉग की शक्ति है), विचारों, मॉडलों, मॉडलों, और व्यापार समाप्तों में बराबर लागू होता है।
पार्ट 1 (यह लेख) एंटिटी फ्रेमवर्क कोर, एसक्यूएल पीढ़ी, तथा सामान्य फन्दों पर ध्यान केंद्रित करता है. पार्ट 2 डी- हॉर, रॉडॉर, रॉटर, वस्तु लाइब्रेरी, और Edss के निकट आ जाएगा.
यदि आप व्यावहारिक ईएफ कोर कार्यान्वयन में रुचि रखते हैं, मेरे अन्य आलेखों की जाँच करें:
.NERT डाटा एक्सेस पार्क को एक स्पेक्ट्रम के रूप में कल्पना की जा सकती है:
Full Abstraction Full Control
↓ ↓
[EF Core] → [EF Core Raw SQL] → [Dapper] → [Npgsql ADO.NET]
जैसा कि आप बाएँ से दाएँ ले जाते हैं, आप प्रदर्शन और नियंत्रण प्राप्त करते हैं, लेकिन सुविधा और स्वचालित विशेषताएँ खो देते हैं. चलो विवरण में प्रत्येक तरीका की जाँच करें.
यहाँ एक दृश्य तुलना है कि कैसे हर एक आम प्रश्न संभालता है:
graph TB
subgraph "EF Core Flow"
A1[LINQ Query] -->|Compile| B1[Expression Tree]
B1 -->|Translate| C1[SQL Query]
C1 -->|Execute| D1[PostgreSQL]
D1 -->|Results| E1[DbDataReader]
E1 -->|Materialize| F1[Tracked Entities]
F1 -->|Return| G1[Application]
end
subgraph "Dapper Flow"
A2[SQL String] -->|Parameterize| B2[DbCommand]
B2 -->|Execute| C2[PostgreSQL]
C2 -->|Results| D2[DbDataReader]
D2 -->|Map| E2[POCOs]
E2 -->|Return| F2[Application]
end
subgraph "Raw Npgsql Flow"
A3[SQL + Parameters] -->|Build Command| B3[NpgsqlCommand]
B3 -->|Execute| C3[PostgreSQL]
C3 -->|Results| D3[NpgsqlDataReader]
D3 -->|Manual Mapping| E3[Objects]
E3 -->|Return| F3[Application]
end
style A1 stroke:#2563eb,stroke-width:2px
style B1 stroke:#2563eb,stroke-width:2px
style C1 stroke:#2563eb,stroke-width:2px
style D1 stroke:#2563eb,stroke-width:2px
style E1 stroke:#2563eb,stroke-width:2px
style F1 stroke:#2563eb,stroke-width:2px
style G1 stroke:#2563eb,stroke-width:2px
style A2 stroke:#059669,stroke-width:2px
style B2 stroke:#059669,stroke-width:2px
style C2 stroke:#059669,stroke-width:2px
style D2 stroke:#059669,stroke-width:2px
style E2 stroke:#059669,stroke-width:2px
style F2 stroke:#059669,stroke-width:2px
style A3 stroke:#dc2626,stroke-width:2px
style B3 stroke:#dc2626,stroke-width:2px
style C3 stroke:#dc2626,stroke-width:2px
style D3 stroke:#dc2626,stroke-width:2px
style E3 stroke:#dc2626,stroke-width:2px
style F3 stroke:#dc2626,stroke-width:2px
graph LR
A[High Productivity<br/>Low Performance] --> B[EF Core<br/>Full Tracking]
B --> C[EF Core<br/>No Tracking]
C --> D[EF Core<br/>Raw SQL]
D --> E[Dapper]
E --> F[Raw Npgsql]
F --> G[Low Productivity<br/>High Performance]
style A stroke:#2563eb,stroke-width:2px
style B stroke:#2563eb,stroke-width:2px
style C stroke:#3b82f6,stroke-width:2px
style D stroke:#059669,stroke-width:2px
style E stroke:#059669,stroke-width:2px
style F stroke:#dc2626,stroke-width:2px
style G stroke:#dc2626,stroke-width:2px
एंटिटी फ्रेमवर्क कोर माइक्रोसॉफ़्ट फ्लेग ओ गिरोह है, आपके डाटाबेस के ऊपर एक पूर्ण शटमा प्रदान करता है. यह एसक्यूएल को समर्थन करता है Npegl. secrummramr. प्रेषित प्रदाता.
आपकी परियोजना में ईएफ को बनाने के लिए व्यावहारिक मार्गदर्शन के लिए, मेरे लेख को देखिए ब्लॉग पोस्ट के लिए एंटिटी फ्रेमवर्क जोड़े.
public class BlogDbContext : DbContext
{
public DbSet<BlogPost> BlogPosts { get; set; }
public DbSet<Comment> Comments { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql("Host=localhost;Database=blog;Username=postgres;Password=secret");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// PostgreSQL-specific: Full-text search
modelBuilder.Entity<BlogPost>()
.HasGeneratedTsVectorColumn(
p => p.SearchVector,
"english",
p => new { p.Title, p.Content })
.HasIndex(p => p.SearchVector)
.HasMethod("GIN");
// PostgreSQL array type
modelBuilder.Entity<BlogPost>()
.Property(p => p.Tags)
.HasPostgresArrayConversion(
tag => tag.ToLowerInvariant(),
tag => tag);
}
}
public class BlogPost
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public string[] Tags { get; set; }
public NpgsqlTsVector SearchVector { get; set; }
public List<Comment> Comments { get; set; }
public DateTime PublishedDate { get; set; }
}
// Usage
public class BlogService
{
private readonly BlogDbContext _context;
public async Task<List<BlogPost>> GetRecentPostsAsync(int count)
{
return await _context.BlogPosts
.Include(p => p.Comments)
.OrderByDescending(p => p.PublishedDate)
.Take(count)
.ToListAsync();
}
public async Task<List<BlogPost>> SearchPostsAsync(string searchTerm)
{
return await _context.BlogPosts
.Where(p => p.SearchVector.Matches(EF.Functions.ToTsQuery("english", searchTerm)))
.ToListAsync();
}
public async Task AddPostAsync(BlogPost post)
{
_context.BlogPosts.Add(post);
await _context.SaveChangesAsync();
}
}
EF कोरल रॉ एसक्यूएल जांच को भी समर्थन देता है जब आपको अधिक नियंत्रण की आवश्यकता होती है:
public async Task<List<BlogPost>> GetPostsByComplexCriteriaAsync()
{
var searchTerm = "postgresql";
return await _context.BlogPosts
.FromSqlInterpolated($@"
SELECT * FROM ""BlogPosts""
WHERE ""SearchVector"" @@ to_tsquery('english', {searchTerm})
AND array_length(""Tags"", 1) > 3
ORDER BY ts_rank(""SearchVector"", to_tsquery('english', {searchTerm})) DESC
")
.ToListAsync();
}
// Or with DbDataReader for maximum control
public async Task<List<PostStatistics>> GetPostStatisticsAsync()
{
using var command = _context.Database.GetDbConnection().CreateCommand();
command.CommandText = @"
SELECT
DATE_TRUNC('month', ""PublishedDate"") as Month,
COUNT(*) as PostCount,
AVG(ARRAY_LENGTH(""Tags"", 1)) as AvgTags
FROM ""BlogPosts""
GROUP BY DATE_TRUNC('month', ""PublishedDate"")
ORDER BY Month DESC";
await _context.Database.OpenConnectionAsync();
var results = new List<PostStatistics>();
using var reader = await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
results.Add(new PostStatistics
{
Month = reader.GetDateTime(0),
PostCount = reader.GetInt32(1),
AverageTags = reader.GetDouble(2)
});
}
return results;
}
डाउनलोड किया जा रहा है
❍ जब आप किसी को ठोकर खाते हैं, तो उसे माफ मत कीजिए:
EF कोर का उपयोग करने के सबसे महत्वपूर्ण पहलुओं में से एक समझ है क्या एसक्यूएल यह उत्पन्न करता है. EF कोर कोर ने सालों के दौरान उल्लेखनीय सुधार किया है, लेकिन यह महत्वपूर्ण है कि CATCT को भेजा जा रहा है.
// Enable sensitive data logging and detailed errors (development only!)
optionsBuilder
.UseNpgsql(connectionString)
.EnableSensitiveDataLogging()
.EnableDetailedErrors()
.LogTo(Console.WriteLine, LogLevel.Information);
// Or use logging to see SQL
public class BlogService
{
private readonly BlogDbContext _context;
private readonly ILogger<BlogService> _logger;
public async Task<List<BlogPost>> GetPostsAsync()
{
var query = _context.BlogPosts
.Where(p => p.PublishedDate > DateTime.UtcNow.AddDays(-30))
.OrderByDescending(p => p.PublishedDate);
// View the SQL before execution
var sql = query.ToQueryString();
_logger.LogInformation("Executing query: {Sql}", sql);
return await query.ToListAsync();
}
}
C# LONQ:
var recentPosts = await _context.BlogPosts
.Where(p => p.CategoryId == 5)
.OrderByDescending(p => p.PublishedDate)
.Take(10)
.ToListAsync();
एसक्यूएल उत्पन्न करें (y)ईएफ कोर 8+):
SELECT b."Id", b."Title", b."Content", b."CategoryId", b."PublishedDate"
FROM "BlogPosts" AS b
WHERE b."CategoryId" = @__categoryId_0
ORDER BY b."PublishedDate" DESC
LIMIT @__p_1
ध्यान दें कि ईएफ कोर 8+ शुद्ध बनाता है, कुशल एसक्यूएल को सही पैरामीटर के साथ साफ करता है. ईएफ कोर १० यह प्रवृत्ति और भी अधिक सुधार के साथ जारी है ।
C# कोड:
var posts = await _context.BlogPosts
.Include(p => p.Category)
.Include(p => p.Comments)
.ToListAsync();
पुराना एसक्यूएल (ईएफ कोर 3. 11 - कार्टियन विस्फोट):
SELECT b."Id", b."Title", c."Id", c."Name", cm."Id", cm."Content"
FROM "BlogPosts" AS b
LEFT JOIN "Categories" AS c ON b."CategoryId" = c."Id"
LEFT JOIN "Comments" AS cm ON b."Id" = cm."BlogPostId"
ORDER BY b."Id", c."Id"
जिसने (हर चीज़ को) पैदा किया कार्टेसियन उत्पाद - अगर एक पोस्ट में 10 टिप्पणी हैं, कि पंक्ति 10 बार दोहराया जाता है!
क्वैरी के साथ C# कोड:
var posts = await _context.BlogPosts
.Include(p => p.Category)
.Include(p => p.Comments)
.AsSplitQuery() // ← This is the key!
.ToListAsync();
एसक्यूएल तैयार करें (M)
-- Query 1: Get posts and categories
SELECT b."Id", b."Title", b."Content", c."Id", c."Name"
FROM "BlogPosts" AS b
LEFT JOIN "Categories" AS c ON b."CategoryId" = c."Id"
-- Query 2: Get comments for those posts
SELECT cm."Id", cm."Content", cm."BlogPostId"
FROM "Comments" AS cm
INNER JOIN (
SELECT b."Id"
FROM "BlogPosts" AS b
) AS t ON cm."BlogPostId" = t."Id"
ORDER BY t."Id"
यह कार्टियन उत्पाद को खत्म करता है और अकसर होता है अधिक तेजी से संग्रह के लिए!
C# कोड:
var posts = await _context.BlogPosts
.Include(p => p.Comments.Where(c => c.IsApproved))
.ToListAsync();
एसक्यूएल बनाएँ:
SELECT b."Id", b."Title", b."Content", t."Id", t."Content", t."IsApproved"
FROM "BlogPosts" AS b
LEFT JOIN (
SELECT c."Id", c."Content", c."IsApproved", c."BlogPostId"
FROM "Comments" AS c
WHERE c."IsApproved" = TRUE
) AS t ON b."Id" = t."BlogPostId"
ORDER BY b."Id"
C# कोड:
public class BlogPost
{
public int Id { get; set; }
public string Title { get; set; }
public PostMetadata Metadata { get; set; } // Stored as JSONB
}
public class PostMetadata
{
public bool IsFeatured { get; set; }
public int ViewCount { get; set; }
public List<string> RelatedTags { get; set; }
}
// Query JSON properties
var featuredPosts = await _context.BlogPosts
.Where(p => p.Metadata.IsFeatured)
.ToListAsync();
एसक्यूएल बनाएँ:
SELECT b."Id", b."Title", b."Metadata"
FROM "BlogPosts" AS b
WHERE b."Metadata" ->> 'IsFeatured' = 'true'
EF कोर 7+ JSON संपत्ति का अनुवाद JSON ऑपरेटरों में कर सकता है!
पुराना मार्ग (प्रयोगात्मक):
var posts = await _context.BlogPosts
.Where(p => p.CategoryId == 5)
.ToListAsync();
foreach (var post in posts)
{
post.IsArchived = true;
}
await _context.SaveChangesAsync(); // Generates N UPDATE statements!
नया मार्ग (ईएफओ कोर 7+):
await _context.BlogPosts
.Where(p => p.CategoryId == 5)
.ExecuteUpdateAsync(setters => setters
.SetProperty(p => p.IsArchived, true));
डी- एसक्यूएल तैयार करें (केवल क्वैरी!):
UPDATE "BlogPosts" AS b
SET "IsArchived" = TRUE
WHERE b."CategoryId" = 5
यह एक है विशाल सुधार - एन के बजाय एक एसक्यूएल कथन!
पुराना:
var oldPosts = await _context.BlogPosts
.Where(p => p.PublishedDate < DateTime.UtcNow.AddYears(-5))
.ToListAsync();
_context.BlogPosts.RemoveRange(oldPosts);
await _context.SaveChangesAsync(); // N DELETE statements
नया मार्ग:
await _context.BlogPosts
.Where(p => p.PublishedDate < DateTime.UtcNow.AddYears(-5))
.ExecuteDeleteAsync();
एसक्यूएल बनाएँ:
DELETE FROM "BlogPosts" AS b
WHERE b."PublishedDate" < @__p_0
C# कोड:
var categoryStats = await _context.Categories
.Select(c => new CategoryStats
{
CategoryName = c.Name,
PostCount = c.BlogPosts.Count(),
LatestPostDate = c.BlogPosts.Max(p => p.PublishedDate),
AverageComments = c.BlogPosts.Average(p => p.Comments.Count)
})
.ToListAsync();
एसक्यूएल तैयार करें (ईएफ कोर 8+/ 10):
SELECT c."Name" AS "CategoryName",
COUNT(*)::int AS "PostCount",
MAX(b."PublishedDate") AS "LatestPostDate",
COALESCE(AVG((
SELECT COUNT(*)::int
FROM "Comments" AS c0
WHERE b."Id" = c0."BlogPostId"
))::double precision, 0.0) AS "AverageComments"
FROM "Categories" AS c
LEFT JOIN "BlogPosts" AS b ON c."Id" = b."CategoryId"
GROUP BY c."Id", c."Name"
पूर्ण पाठ खोज में एक गहरी तेज़ी के लिए, मेरे लेख को देखें ईएफ कोर के साथ पूर्ण पाठ खोज को लागू कर रहा है.
C# कोड:
var searchResults = await _context.BlogPosts
.Where(p => p.SearchVector.Matches(EF.Functions.ToTsQuery("english", "postgresql & performance")))
.OrderByDescending(p => p.SearchVector.Rank(EF.Functions.ToTsQuery("english", "postgresql & performance")))
.Take(20)
.ToListAsync();
एसक्यूएल बनाएँ:
SELECT b."Id", b."Title", b."Content", b."SearchVector"
FROM "BlogPosts" AS b
WHERE b."SearchVector" @@ to_tsquery('english', @__searchTerm_0)
ORDER BY ts_rank(b."SearchVector", to_tsquery('english', @__searchTerm_0)) DESC
LIMIT 20
समस्या:
// ❌ DANGER: This can cause memory leaks!
public class PostCache
{
private readonly BlogDbContext _context;
private List<BlogPost> _cachedPosts;
public PostCache(BlogDbContext context)
{
_context = context;
}
public async Task LoadCacheAsync()
{
// These entities are now tracked by the context
_cachedPosts = await _context.BlogPosts.ToListAsync();
// The DbContext holds references to these entities FOREVER
// They can never be garbage collected while the context lives!
}
}
क्यों यह एक समस्या है:
DbContextसमाधानः
public async Task LoadCacheAsync()
{
// ✅ Use AsNoTracking() for read-only queries
_cachedPosts = await _context.BlogPosts
.AsNoTracking()
.ToListAsync();
// Or detach entities after loading
var posts = await _context.BlogPosts.ToListAsync();
foreach (var post in posts)
{
_context.Entry(post).State = EntityState.Detached;
}
_cachedPosts = posts;
}
खतरे: अगर आप कमज़ोर पड़ गए हैं, तो कम - से - कम गैर - ज़रूरी चीज़ों का इस्तेमाल मत कीजिए
प्रॉक्सी + क कैशिंग = जी.
यदि आप प्रॉक्सी सक्षम हैं, आप डीबी संदर्भ उदाहरण या कैश एंटिटीज़ को कैश करते हैं, आप विल रिसाव मेमोरी. प्रॉक्सी यांत्रिकी डीबी संदर्भ को संदर्भ बनाए रखती है, कचरे के संग्रह को रोक रही है. यह ईएफ कोर अनुप्रयोगों में सबसे आम और खतरनाक ग़लत ग़लतियों में से एक है.
लघुछवियों का नियम: हमेशा संग्रह को साफ - सफाई के साथ शामिल कीजिए
.Include()सिर्फ प्रॉक्सी का उपयोग करें यदि आप पूरी तरह से जानते हैं और कभी नहीं, हमेशा कैश प्रॉक्सी एंटिटी.
समस्या 1: N+1 प्रश्न दुःस्वप्न
// ❌ Enable lazy loading
optionsBuilder
.UseNpgsql(connectionString)
.UseLazyLoadingProxies(); // Convenient but dangerous!
public class BlogPost
{
public int Id { get; set; }
public string Title { get; set; }
public virtual Category Category { get; set; } // Virtual = proxy
public virtual List<Comment> Comments { get; set; }
}
// Somewhere in your code
var posts = await _context.BlogPosts.ToListAsync();
foreach (var post in posts)
{
Console.WriteLine(post.Category.Name); // N+1 query here!
Console.WriteLine(post.Comments.Count); // Another N+1 query!
}
क्या होता है:
Category डाटाबेस क्वैरी ट्रिगर करता हैComments अन्य क्वैरी ट्रिगर करता हैसमस्या 2: प्रॉक्सी + कलिंग = मेमोरी लीक
// ❌ CATASTROPHIC: Lazy loading proxies + caching
public class BlogPostCache
{
private static List<BlogPost> _cachedPosts;
private readonly BlogDbContext _context;
public BlogPostCache()
{
var optionsBuilder = new DbContextOptionsBuilder<BlogDbContext>();
optionsBuilder
.UseNpgsql(connectionString)
.UseLazyLoadingProxies(); // ⚠️ DANGER!
_context = new BlogDbContext(optionsBuilder.Options);
}
public async Task<List<BlogPost>> GetCachedPostsAsync()
{
if (_cachedPosts == null)
{
// ❌ These proxy entities hold references to _context
_cachedPosts = await _context.BlogPosts.ToListAsync();
}
return _cachedPosts;
}
}
क्यों यह विनाशकारी है:
DbContextDbContext सभी निश्चित निगमों का संदर्भ बनाए रखता हैहल: समझदारी से काम लीजिए
// ✅ NEVER use lazy loading proxies - always be explicit
optionsBuilder
.UseNpgsql(connectionString);
// NO .UseLazyLoadingProxies()!
public class BlogPost
{
public int Id { get; set; }
public string Title { get; set; }
public Category Category { get; set; } // NOT virtual
public List<Comment> Comments { get; set; } // NOT virtual
}
// ✅ Explicit eager loading - you control what's loaded
var posts = await _context.BlogPosts
.Include(p => p.Category)
.Include(p => p.Comments)
.ToListAsync();
// ✅ Or use split queries for better performance
var posts = await _context.BlogPosts
.Include(p => p.Category)
.Include(p => p.Comments)
.AsSplitQuery()
.ToListAsync();
// ✅ Or use projection to DTOs (best for caching)
var posts = await _context.BlogPosts
.Select(p => new PostDto
{
Title = p.Title,
CategoryName = p.Category.Name,
CommentCount = p.Comments.Count
})
.ToListAsync();
// ✅ If you MUST cache, use AsNoTracking and no proxies
public class SafeBlogPostCache
{
private static List<BlogPost> _cachedPosts;
private readonly IDbContextFactory<BlogDbContext> _contextFactory;
public async Task<List<BlogPost>> GetCachedPostsAsync()
{
if (_cachedPosts == null)
{
using var context = await _contextFactory.CreateDbContextAsync();
_cachedPosts = await context.BlogPosts
.Include(p => p.Category)
.Include(p => p.Comments)
.AsNoTracking() // Critical for caching!
.ToListAsync();
}
return _cachedPosts;
}
}
जब बीमारियाँ स्वीकार्य हो सकती हैं (संत्र बंद हो जाता है):
प्रॉक्सी लोड करने पर सिर्फ तभी स्वीकार्य हो सकता है:
लेकिन फिर भी, स्पष्ट Include() लगभग हमेशा बेहतर विकल्प है क्योंकि:
उत्पादन में जीवन - अवधि का प्रबंधन करने के बारे में अधिक जानकारी के लिए, मेरे लेख को देखिए EF उत्प्रवासन सही दिशा दिखाता है.
समस्या:
// ❌ NEVER do this - singleton DbContext
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<BlogDbContext>(); // WRONG!
}
// ❌ Also wrong - storing context in static field
public static class DataAccess
{
private static BlogDbContext _context = new BlogDbContext();
public static async Task<BlogPost> GetPostAsync(int id)
{
return await _context.BlogPosts.FindAsync(id);
}
}
क्यों गलत है:
DbContext है थ्रेड नहीं निर्मित करेंसमाधानः
// ✅ Use scoped lifetime (default in ASP.NET Core)
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<BlogDbContext>(options =>
options.UseNpgsql(connectionString));
}
// ✅ Or use DbContext factory for background services
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContextFactory<BlogDbContext>(options =>
options.UseNpgsql(connectionString));
}
public class BlogBackgroundService
{
private readonly IDbContextFactory<BlogDbContext> _contextFactory;
public async Task ProcessPostsAsync()
{
// Create a new context for this operation
using var context = await _contextFactory.CreateDbContextAsync();
var posts = await context.BlogPosts.ToListAsync();
// Process posts...
}
}
समस्या:
public class BlogPost
{
public int Id { get; set; }
public string Title { get; set; }
public List<Comment> Comments { get; set; }
}
// You query one post...
var post = await _context.BlogPosts.FirstAsync();
// Add a new comment
var newComment = new Comment { Content = "Great post!" };
post.Comments.Add(newComment);
await _context.SaveChangesAsync();
// ❌ EF Core saves the comment, BUT...
// If Comments wasn't loaded, you just lost all existing comments!
// The collection is empty, so EF thinks there are no other comments
समाधानः
// ✅ Always load navigation properties before modifying
var post = await _context.BlogPosts
.Include(p => p.Comments)
.FirstAsync(p => p.Id == postId);
post.Comments.Add(newComment);
await _context.SaveChangesAsync();
// Or add directly to the DbSet
_context.Comments.Add(new Comment
{
BlogPostId = postId,
Content = "Great post!"
});
await _context.SaveChangesAsync();
समस्या:
// ❌ Mixing sync and async - deadlock risk!
public async Task<BlogPost> GetPostAsync(int id)
{
var post = _context.BlogPosts
.Where(p => p.Id == id)
.FirstOrDefault(); // Sync method in async context!
return post;
}
// ❌ Even worse - blocking async code
public BlogPost GetPost(int id)
{
return _context.BlogPosts
.FirstOrDefaultAsync(p => p.Id == id)
.Result; // DEADLOCK RISK!
}
समाधानः
// ✅ Use async all the way
public async Task<BlogPost> GetPostAsync(int id)
{
return await _context.BlogPosts
.FirstOrDefaultAsync(p => p.Id == id);
}
// ✅ Or use sync all the way (not recommended for ASP.NET Core)
public BlogPost GetPost(int id)
{
return _context.BlogPosts
.FirstOrDefault(p => p.Id == id);
}
के साथ ईएफ कोर १० 10 के साथ रिहा किए गए .NT 10 में बहुत से महत्वपूर्ण परिवर्तन हैं जब अद्यतन किया जा रहा है. पूरे सूची के लिए देखें. ईएफ कोर 10 में बदलावों को तोड़ रहे हैं.
ईएफ कोर 10 की जरूरत है .नेट 10. यह नहीं चला जाएगा .NT 8, eET 9, or eET फ्रेमवर्क. यह सबसे महत्वपूर्ण परिवर्तन है - सुनिश्चित करें कि आपके परियोजना लक्ष्य को साफ करें net10.0 अद्यतन से पहले.
ईएफ कोर 10 परिवर्तन कैसे करें Contains() एसक्यूएल को उपयोग में लाया जाता है. पहले, ईएफ को प्रयोग में लिया जाता है OpenJson() ( एसक्यूएल सर्वर) या समान. अब यह डिफ़ॉल्ट है. छैतिज पैमाना इससे बेहतर क्वैरी योजना कैशिंग प्रदान होती है.
प्रभाव: आप अन्य एसक्यूएल को भी देख सकते हैं जैसे कि चरनी के लिए बनाया गया:
var ids = new List<int> { 1, 2, 3, 4, 5 };
var posts = await _context.BlogPosts
.Where(p => ids.Contains(p.Id))
.ToListAsync();
EF कोर 8/9 (फ़ाइलेन):
SELECT b."Id", b."Title"
FROM "BlogPosts" AS b
WHERE b."Id" IN (SELECT value FROM OPENJSON(@__ids_0))
EF कोर 10 (मीटर ऐरे):
SELECT b."Id", b."Title"
FROM "BlogPosts" AS b
WHERE b."Id" = ANY(@__ids_0) -- PostgreSQL
-- Or: WHERE b."Id" IN (@__ids_0_0, @__ids_0_1, @__ids_0_2, ...) -- SQL Server
यदि आप अनुभव करते हैं प्रदर्शन रीग्रेसन, पुराने व्यवहार में वापस आता है:
// SQL Server
optionsBuilder.UseSqlServer(connectionString,
o => o.UseParameterizedCollectionMode(ParameterTranslationMode.Constant));
// PostgreSQL - generally parameter arrays work well, but you can opt out if needed
वह ExecuteUpdateAsync हस्ताक्षर ग़ैर- कुशल भेड़ के मेम्ने को समर्थन देने के लिए परिवर्तित किया गया है. यह ज्यादा ढीली है लेकिन यह कुछ भी नहीं करता है. ब्रेक कोड जो एक्सप्रेशन ट्री प्रोज़ेक्टिव रूप से बनाया गया है:
पुराना तरीका (केर कोर 7- 9):
// This still works
await _context.BlogPosts
.Where(p => p.CategoryId == 5)
.ExecuteUpdateAsync(setters => setters
.SetProperty(p => p.IsArchived, true));
नया ईएफ कोर १० - नॉन- स्प्क्शन भेड़ के बच्चे:
// Now you can include custom logic!
await _context.BlogPosts
.Where(p => p.CategoryId == 5)
.ExecuteUpdateAsync(setters =>
{
setters.SetProperty(p => p.IsArchived, true);
setters.SetProperty(p => p.UpdatedAt, DateTime.UtcNow);
// Can now include conditional logic, loops, etc.
});
ईएफ कोर 10 बदल देते हैं कि कैसे जटिल किस्म के स्तम्भ डेटा भ्रष्टाचार को रोकने के लिए रखे जाते हैं:
ईएफ कोर 9:
NestedComplex_Property
ईएफ कोर १०: १
OuterComplex_NestedComplex_Property
उत्प्रवासन प्रभाव: यदि आपके पास विविध क़िस्मों के मौजूदा तालिका हैं, तो आपको स्तम्भों का नाम बदलना या सुस्पष्ट स्तम्भों के नामों को कॉन्फ़िगर करना होगा:
modelBuilder.Entity<Order>()
.ComplexProperty(o => o.ShippingAddress)
.Property(a => a.Street)
.HasColumnName("ShippingAddress_Street"); // Explicit name
क्वीप एसक्यूएल डाटाबेस या एसक्यूएल सर्वर के लिए 2025 (प्रयोगात्मक स्तर 170+), EF कोर को नए निवासियों के लिए डिफ़ॉल्ट बनाता है JSON डाटा क़िस्म इसके बजाए NVARCHAR(MAX).
स्तर बनाए रखने के लिए (यदि आपको पीछे की संगतता की आवश्यकता है):
optionsBuilder.UseAzureSql(connectionString,
o => o.UseCompatibilityLevel(160)); // Use old NVARCHAR behavior
EF कोर 8/9 से ईएफ को कम करने के दौरान
net10.0Microsoft.EntityFrameworkCore.* पैकेज को 10xNpgsql.EntityFrameworkCore.PostgreSQL 10x में.Contains() प्रदर्शन परिवर्तनों के लिए संग्रह सहितExecuteUpdateAsync एक्सप्रेशनInclude() या विभाजन उचित रूप सेLIKE चरtsvector स्तंभ संगठनों के साथअगले लेख में, हम खोजेंगे:
इस ब्लॉग पर संबंधित आलेख:
भाग 2 में, हम Dapppsse, रॉ Npsqucqul में कटौती करेंगे, और जांच करें कि कैसे बहुतम प्रदर्शन के लिए और बनाए रखने के लिए।
© 2026 Scott Galloway — Unlicense — All content and source code on this site is free to use, copy, modify, and sell.