|
| 1 | +// Example program for EFCore with CrateDB. |
| 2 | + |
| 3 | +// Npgsql Entity Framework Core provider for PostgreSQL |
| 4 | +// https://github.com/npgsql/efcore.pg |
| 5 | +using System; |
| 6 | +using System.Linq; |
| 7 | +using Microsoft.EntityFrameworkCore; |
| 8 | + |
| 9 | +public class Blog |
| 10 | +{ |
| 11 | + public long Id { get; set; } |
| 12 | + public required string Name { get; set; } |
| 13 | +} |
| 14 | + |
| 15 | +public class BloggingContext : DbContext |
| 16 | +{ |
| 17 | + public DbSet<Blog> Blogs { get; set; } |
| 18 | + |
| 19 | + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) |
| 20 | + => optionsBuilder.UseNpgsql(@"Host=localhost;Username=crate;Password=;Database=testdrive"); |
| 21 | +} |
| 22 | + |
| 23 | +class BlogDemo |
| 24 | +{ |
| 25 | + public BloggingContext context; |
| 26 | + |
| 27 | + public static void Main(string[] args) |
| 28 | + { |
| 29 | + var blogDemo = new BlogDemo(); |
| 30 | + blogDemo.run(); |
| 31 | + } |
| 32 | + |
| 33 | + public BlogDemo() |
| 34 | + { |
| 35 | + // Provide context and turn off transactions. |
| 36 | + context = new BloggingContext(); |
| 37 | + context.Database.AutoTransactionBehavior = AutoTransactionBehavior.Always; |
| 38 | + context.Database.AutoSavepointsEnabled = false; |
| 39 | + |
| 40 | + // CrateDB does not implement 'DROP DATABASE'. |
| 41 | + // await context.Database.EnsureDeleted(); |
| 42 | + context.Database.EnsureCreated(); |
| 43 | + } |
| 44 | + |
| 45 | + public void run() |
| 46 | + { |
| 47 | + RunDDL(); |
| 48 | + EfCoreWorkload(); |
| 49 | + } |
| 50 | + |
| 51 | + public void RunDDL() |
| 52 | + { |
| 53 | + context.Database.ExecuteSqlRaw(""" |
| 54 | + CREATE TABLE IF NOT EXISTS "Blogs" |
| 55 | + ("Id" bigint GENERATED ALWAYS AS NOW(), "Name" text); |
| 56 | + """); |
| 57 | + } |
| 58 | + |
| 59 | + public void EfCoreWorkload() |
| 60 | + { |
| 61 | + |
| 62 | + // Insert a Blog. |
| 63 | + context.Blogs.Add(new() { Name = "FooBlog" }); |
| 64 | + context.SaveChanges(); |
| 65 | + |
| 66 | + // For converging written data immediately, submit a cluster-wide flush operation. |
| 67 | + // https://cratedb.com/docs/crate/reference/en/latest/sql/statements/refresh.html#sql-refresh |
| 68 | + context.Database.ExecuteSqlRaw("""REFRESH TABLE "Blogs";"""); |
| 69 | + |
| 70 | + // Query all blogs whose name starts with F. |
| 71 | + var fBlogs = context.Blogs.Where(b => b.Name.StartsWith("F")).ToList(); |
| 72 | + |
| 73 | + // Output the results to the console. |
| 74 | + foreach (var blog in fBlogs) |
| 75 | + { |
| 76 | + Console.WriteLine($"Blog Id: {blog.Id}, Blog Name: {blog.Name}"); |
| 77 | + } |
| 78 | + } |
| 79 | +} |
0 commit comments