Created
August 16, 2024 08:42
-
-
Save nihat-js/15ded9f2ea3c4a972e9f8b1e8380fc4d to your computer and use it in GitHub Desktop.
Entity Framework Core with SQL Server Crud Sample
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; | |
using System.Numerics; | |
Console.WriteLine("Hello, World!"); | |
var context = new ApplicationContext(); | |
while (true) { | |
Console.WriteLine("" + | |
"1 => Read All Users" + | |
"2=> Add User " + | |
"3 => Delete user"); | |
string answer = Console.ReadLine(); | |
if (answer == "1") { | |
var users = context.Users.ToList(); | |
foreach (var user in users) { | |
Console.WriteLine(user.Id + " " + user.Name + " " + user.Surname + " => " + user.Email); | |
} | |
} else if (answer == "2") { | |
Console.WriteLine("Name"); | |
string name = Console.ReadLine(); | |
Console.WriteLine("Surname"); | |
string surname = Console.ReadLine(); | |
Console.WriteLine("Email"); | |
string email = Console.ReadLine(); | |
var newUser = new User(); | |
newUser.Name = name; | |
newUser.Surname = surname; | |
newUser.Email = email; | |
context.Add(newUser); | |
context.SaveChanges(); | |
} else if (answer == "3") { | |
Console.WriteLine("Enter Id"); | |
int id = int.Parse(Console.ReadLine()); | |
var user = await context.Users.FindAsync(id); | |
if (user != null) { | |
Console.WriteLine("deleting"); | |
context.Users.Remove(user); | |
await context.SaveChangesAsync(); | |
} | |
} | |
} | |
public class ApplicationContext : DbContext { | |
public DbSet<User> Users { get; set; } | |
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { | |
optionsBuilder.UseSqlServer( | |
"Server= localhost;Database=nihat;User Id=sa;Password=123456;Trusted_Connection=True;TrustServerCertificate=True;" | |
); | |
} | |
} | |
public class User { | |
public int Id { get; set; } | |
public string Name { get; set; } | |
public string Surname { get; set; } | |
public string Email { get; set; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment