Database Project

 avatar
unknown
csharp
a year ago
2.1 kB
4
Indexable
using Microsoft.EntityFrameworkCore;

internal class Program
{
	// DB - DataBase - БД - База данных
	// Реляционные и Не Реляционные (SQL-DB / NO SQL-DB)
	// СУБД -
	// (SQL) MySQL, SQL Server(SQLite/MSSQL), Postgre ...
	// (NO-SQL) MongoDB, MariaDB, CosmosDB ...
	// SQL - Язык запросов
	// ORM - EntityFramework

	private static void Main(string[] args)
	{
		ApplicationDbContext context = new ApplicationDbContext();

		while (true)
		{
			Console.Clear();

			if (!context.Books.Any())
			{
				Console.WriteLine("В таблице книг нет данных");
				return;
			}


			Console.WriteLine("Все книги: ");

			foreach (var book in context.Books)
			{
				Console.WriteLine(book.Name);
			}

			Console.ReadKey();
		}

		Console.WriteLine("Для добавления в БД новой книги введите данные в формате");
		Console.WriteLine("ИМЯ ЗАГОЛОВОК ОПИСАНИЕ АВТОР");
		string inputBook = Console.ReadLine();

		Book newBook = new Book()
		{
			Name = inputBook.Split(' ')[0],
			Title = inputBook.Split(' ')[1],
			Description = inputBook.Split(' ')[2],
			Author = inputBook.Split(' ')[3],
		};

		context.Books.Add(newBook);
		context.SaveChanges();
	}

}

public class Book
{
	public int Id { get; set; }
	public string Name { get; set; }
	public string Title { get; set; }
	public string Description { get; set; }
	public string Author { get; set; }
}

public class ApplicationDbContext : DbContext
{
	// Создание таблицы Books в БД
	public DbSet<Book> Books { get; set; }

	public ApplicationDbContext()
	{
		Database.EnsureCreated();
	}

	protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
	{
		// Подключение к SQL Server по строке подключения
		optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=BookDB;Trusted_Connection=True");
	}
}
Leave a Comment