using System;
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.SqlServer;
namespace DatabaseExaple_6._0
{
internal class Program
{
static void Main(string[] args)
{
AddExample_EX();
GetExample();
DelteAllExample();
GetExample();
//DeleteByKeyExample();
//GetExample();
}
public static void AddExample()
{
using (var db1 = new BookContext())
{
Book book1 = new Book() { Title = "book1", Author = "The author" };
db1.Books.Add(book1);
Book book2 = new Book() { Title = "book2", Author = "The author 2" };
db1.Books.Add(book2);
db1.Database.EnsureCreated();
db1.SaveChanges();
}
}
public static void AddExample_EX() {
using(var db1 = new BookContext())
{
for (int i = 0; i < 10000; i++)
{
db1.Books.Add(new Book() { Title = GetRdName(), Author = GetRdName()}) ;
}
db1.SaveChanges();
}
}
public static void DelteAllExample()
{
using(var db1 = new BookContext())
{
var AllData = db1.Books.Select(x => x).ToList();
if(AllData != null)
{
db1.Books.RemoveRange(AllData);
}
db1.SaveChanges() ;
}
}
public static void GetExample()
{
using (var db1 = new BookContext())
{
var query = from b in db1.Books
orderby b.Title
select b;
Console.WriteLine("All books in the database:");
foreach (var b in query)
{
Console.WriteLine($"{b.Title} by {b.Author}, code={b.Code}");
}
}
}
public static void DeleteByKeyExample()
{
using (var db1 = new BookContext())
{
var book = db1.Books.Find(1);
if (book != null)
{
db1.Books.Remove(book);
db1.SaveChanges();
}
}
}
public static void DeleteByFoundExample()
{
using (var db1 = new BookContext())
{
var book = db1.Books.First(x => x.Title == "book1");
if(book != null)
{
db1.Books.Remove(book);
}
db1.SaveChanges();
}
}
public static void FindAllBooksExample()
{
using (var db1 = new BookContext())
{
var books = db1.Books.Where(b => b.Title == "book1").ToList();
foreach (var book in books)
{
Console.WriteLine(book.Author);
}
}
}
public static void sqllocaldb_stop_DeleteDataBase()
{
//net start "SQL Server (MSSQLSERVER)"
//sqllocaldb stop
//sqllocaldb delete
}
private static Random rd = new Random();
private static string GetRdName()
{
string name = "";
for (int i = 0; i < 5; i++)
{
name += (char)rd.Next(65, 122);
}
return name;
}
}
public class BookContext : DbContext {
public DbSet<Book> Books { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=(LocalDB)\MSSQLLocalDB;Database=Books;Integrated Security=True");
}
}
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
[Key] public int Code { get; set; }
}
}