Skip to content

Instantly share code, notes, and snippets.

@ravindUwU
Last active October 4, 2023 11:48
Show Gist options
  • Save ravindUwU/89c1c9b028e7455af5dab475d9f1ea5b to your computer and use it in GitHub Desktop.
Save ravindUwU/89c1c9b028e7455af5dab475d9f1ea5b to your computer and use it in GitHub Desktop.
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
public partial class Program
{
[Table("entity")]
[PrimaryKey(nameof(Id))]
class Entity
{
[Column("id")]
public int Id { get; set; }
[Column("col_1")]
public string Col1 { get; set; } = default!;
[Column("col_2")]
public string Col2 { get; set; } = default!;
}
partial class Db : DbContext
{
public DbSet<Entity> Entities { get; set; } = default!;
}
public static async Task Main()
{
var db = new Db();
Write("SELECT *");
await db.Entities.ToListAsync();
Write("Dictionary of (Id, Col1) with (await Select().ToListAsync()).ToDictionary()");
(await db.Entities
.Select((e) => new { e.Id, e.Col1 })
.ToListAsync())
.ToDictionary((e) => e.Id, (e) => e.Col1);
Write("Dictionary of (Id, Col1) with ToDictionaryAsync()");
await db.Entities
.ToDictionaryAsync((e) => e.Id, (e) => e.Col1);
}
partial class Db
{
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
builder.UseSqlServer(_ConnectionString("localhost", "temp"));
builder.LogTo(Console.WriteLine, LogLevel.Information);
}
}
public static void Write(string m)
{
var oldForeground = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine($"\n{m}");
Console.ForegroundColor = oldForeground;
}
}
SELECT *
info: 4/10/2023 22:27:36.805 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (53ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT [e].[id], [e].[col_1], [e].[col_2]
FROM [entity] AS [e]
Dictionary of (Id, Col1) with (await Select().ToListAsync()).ToDictionary()
info: 4/10/2023 22:27:36.997 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (3ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT [e].[id] AS [Id], [e].[col_1] AS [Col1]
FROM [entity] AS [e]
Dictionary of (Id, Col1) with ToDictionaryAsync()
info: 4/10/2023 22:27:37.006 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT [e].[id], [e].[col_1], [e].[col_2]
FROM [entity] AS [e]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment