Created
January 26, 2024 15:28
-
-
Save ievgiienko/7e1d5c79521ddc3126141bddfd1dc21d to your computer and use it in GitHub Desktop.
.NET Core EF Test
This file contains 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 System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using Microsoft.Extensions.Logging; | |
using Microsoft.EntityFrameworkCore; | |
namespace TestEF | |
{ | |
public class User | |
{ | |
public int Id { get; set; } // Primary Key | |
public string? Name { get; set; } | |
public string? Phone { get; set; } | |
} | |
public class MyDbContext : DbContext | |
{ | |
public DbSet<User> Users { get; set; } | |
public static readonly LoggerFactory _myLoggerFactory = | |
new LoggerFactory(new[] { | |
new Microsoft.Extensions.Logging.Debug.DebugLoggerProvider() | |
}); | |
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) | |
{ | |
optionsBuilder | |
.UseLoggerFactory(_myLoggerFactory) | |
.UseMySQL("server=localhost;database=mydb;user=root;password=password"); | |
} | |
} | |
} |
This file contains 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
// See https://aka.ms/new-console-template for more information | |
using TestEF; | |
Console.WriteLine("Hello, World!"); | |
using (var context = new MyDbContext()) | |
{ | |
var user = new User { Name = "John Doe", Phone = "1234567890" }; | |
context.Users.Add(user); | |
context.SaveChanges(); | |
} | |
using (var context = new MyDbContext()) | |
{ | |
var user = context.Users.FirstOrDefault(); | |
if (user != null) | |
{ | |
user.Phone = "0501112233"; // Change the phone number | |
context.SaveChanges(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment