Last active
October 7, 2020 05:56
-
-
Save Ch3shireDev/1e2ed3359e054eb4f80c42044e287bef to your computer and use it in GitHub Desktop.
Minimal example for Entity Framework Core
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using Microsoft.EntityFrameworkCore; | |
| namespace EFCoreExample | |
| { | |
| internal class Program | |
| { | |
| // Install Microsoft.EntityFrameworkCore and Microsoft.EntityFrameworkCore.SqlServer nuget packages. | |
| private static void Main(string[] args) | |
| { | |
| var optionsBuilder = new DbContextOptionsBuilder<AppDbContext>(); | |
| var context = new AppDbContext(optionsBuilder.Options); | |
| context.Database.EnsureDeleted(); | |
| context.Database.EnsureCreated(); | |
| var element = new Element {Content = "abc"}; | |
| context.Elements.Add(element); | |
| context.SaveChanges(); | |
| } | |
| } | |
| internal class AppDbContext : DbContext | |
| { | |
| public DbSet<Element> Elements { get; set; } | |
| public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } | |
| protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) | |
| { | |
| if (!optionsBuilder.IsConfigured) | |
| { | |
| //get connection string from https://www.connectionstrings.com/sql-server/ | |
| optionsBuilder.UseSqlServer("<connection string>"); | |
| } | |
| } | |
| } | |
| internal class Element | |
| { | |
| public int Id { get; set; } | |
| public string Content { get; set; } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment