using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace ConsoleApp6
{
[Table("Books")]
public class Book
{
public int BookId { get; set; }
[Required]
[StringLength(50)]
public String Title { get; set; }
[StringLength(50)]
public String Publisher { get; set; }
}
}
namespace ConsoleApp6
{
public class BooksContext:DbContext
{
public BooksContext(DbContextOptions<BooksContext> options) : base(options) { }
public DbSet<Book> Books { get; set; }
}
}
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp6
{
public class BooksService
{
private readonly BooksContext booksContext;
public BooksService(BooksContext context) => booksContext = context;
public async Task AddBooksAsync()
{
var b1 = new Book
{
Title = "New one",
Publisher = "new p"
};
var b2 = new Book
{
Title = "new Two",
Publisher = "new p2"
};
var b3 = new Book
{
Title = "new three",
Publisher = "new p3"
};
await booksContext.AddRangeAsync(b1, b2, b3);
int records = await booksContext.SaveChangesAsync();
Console.WriteLine($"{records} records added");
Console.WriteLine();
}
public async Task ReadBooksAsync()
{
List<Book> books = await booksContext.Books.ToListAsync();
foreach (var b in books)
{
Console.WriteLine($"{b.Title} {b.Publisher}");
}
Console.WriteLine();
}
}
}
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace ConsoleApp6
{
class Program
{
static async Task Main(string[] args)
{
InitialzeService();
ConfigureLogging();
var services = Container.GetService<BooksService>();
await services.AddBooksAsync();
await services.ReadBooksAsync();
Console.ReadKey();
}
public static ServiceProvider Container { get; private set; }
private static void InitialzeService()
{
const string ConnectionString =
@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=WroxBooks;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
var services = new ServiceCollection();
services.AddTransient<BooksService>()
.AddEntityFrameworkSqlServer()
.AddDbContext<BooksContext>(option =>
option.UseSqlServer(ConnectionString));
Container = services.BuildServiceProvider();
}
private static void ConfigureLogging()
{
ILoggerFactory logger = Container.GetService<ILoggerFactory>();
logger.AddConsole(LogLevel.Information);
}
}
}