public async Task TestData() { //await RoundHouseHelpers.ResetDatabase(new SqlConnection("Server=.;Database=pokemons-test;User Id=sa;Password=Password_123;MultipleActiveResultSets=true")); var result = RoundHouseHelpers.MigrateSql(@"C:\Users\devil\source\repos\DatabaseProviders\GettingStarted.AspNetCore.Api\Infrastructure\Persistence\Migrations\sql", "Server=.;Database=pokemons-test;User Id=sa;Password=Password_123;MultipleActiveResultSets=true", "pokemons-test"); var configuration = new ConfigurationBuilder().AddInMemoryCollection( new Dictionary <string, string> { { "ConnectionStrings:Pokemons", "Server=.;Database=pokemons-test;User Id=sa;Password=Password_123;MultipleActiveResultSets=true" }, } ).Build(); var options = new DbContextOptionsBuilder <PokemonDbContext>(); options.UseSqlServer("Server=.;Database=pokemons-test;User Id=sa;Password=Password_123;MultipleActiveResultSets=true"); var dbContext = new PokemonDbContext(options.Options); var repo = new PokemonsSql(configuration, dbContext); var pokemon = new Api.Domain.Pokemon { Id = new Guid("1eb892bb-69a0-4677-b093-843f713fade9"), Name = "paco" }; await repo.Create(pokemon); await repo.SaveChangesAsync(); var data = await repo.GetPokemonsAsync(); Assert.NotNull(data); await RoundHouseHelpers.ResetDatabase(new SqlConnection("Server=.;Database=pokemons-test;User Id=sa;Password=Password_123;MultipleActiveResultSets=true")); }
// show all pokemon including their types and evolutions private static void DisplayPokemon(DbContextOptions <PokemonDbContext> options) { using (var dbContext = new PokemonDbContext(options)) { // Entity Framework is more like disconnected architecture than connected, // but it's a higher livel of abstraction than both. if (!dbContext.Pokemon.Any()) { Console.WriteLine("No pokemon found!"); } else { foreach (Pokemon pokemon in dbContext.Pokemon.Include(x => x.Type)) { var str = $"{pokemon.PokemonId}: {pokemon.Name} ({pokemon.Height})"; if (pokemon.Evolution != null) { str += $" [{pokemon.Evolution}]"; } str += $", {pokemon.Type.Name}"; // error - Type is null, but it shouldn't be?? Console.WriteLine(str); } } } }
static void AddNewPokemon(PokemonDbContext context) { // check if already exists if (context.Pokemon.Any(p => p.Name == "Charmander")) { Console.WriteLine("Charmander already exists; not adding again"); return; } var charmander = new Pokemon { Name = "Charmander", Height = 6, Weight = 85 }; var fireType = context.Type.FirstOrDefault(t => t.Name == "Fire") ?? new DataAccess.Entities.Type { Name = "Fire" }; charmander.PokemonType.Add(new PokemonType { Type = fireType }); context.Pokemon.Add(charmander); // there are foreign key properties I have not connected up - that's fine // there are navigation properties i have not connected up - that's also fine context.SaveChanges(); }
// add some new pokemon (whether hardcoded, or user input) private static void AddNewPokemon(DbContextOptions <PokemonDbContext> options) { using (var dbContext = new PokemonDbContext(options)) { if (!dbContext.Pokemon.Any(x => x.Name == "Charmander")) { // ^ is converted to a SELECT/FROM/WHERE, runs in the DB, not in the C#. var newPokemon = new Pokemon { Name = "Charmander", Height = 36, Type = dbContext.Type.FirstOrDefault(x => x.Name == "Fire") ?? new Type { Name = "Fire" } }; dbContext.Pokemon.Add(newPokemon); dbContext.SaveChanges(); // add the new pokemon and also the new type. } else { Console.WriteLine("Charmander already exists... doing nothing."); } } }
public JsonResult AfterInput(Pokemon pokes) { PokemonDbContext database = new PokemonDbContext(); database.Pokemans.Add(pokes); database.SaveChanges(); return(Json(pokes)); }
static void AddNewPokemon(PokemonDbContext context) { using (var db = new PokemonDbContext()) { db.Add(new Pokemon { "Coltron" }); db.SaveChanges(); } }
public static void InitializeDatabase(PokemonDbContext db) { var admin = InitializeAdmin(); var abilities = InitializeAbilities(); var pokemon = InitializePokemon(); db.Admins.Add(admin); db.Abilities.AddRange(abilities); db.Pokemons.AddRange(pokemon); db.SaveChanges(); }
static void DisplayPokemon(PokemonDbContext context) { foreach (Pokemon pokemon in context.Pokemon .Include(p => p.PokemonType) .ThenInclude(pt => pt.Type)) { string types = string.Join(", ", pokemon.PokemonType.Select(pt => pt.Type.Name)); if (types.Length == 0) { types = "[none]"; } Console.WriteLine($"Pokemon {pokemon.Name} (type {types})"); } }
private static void DeleteSomePokemon(DbContextOptions <PokemonDbContext> options) { using (var dbContext = new PokemonDbContext(options)) { if (dbContext.Pokemon.FirstOrDefault(x => x.Name == "Charmander") is Pokemon charmander) { dbContext.Pokemon.Remove(charmander); dbContext.SaveChanges(); } else { Console.WriteLine("Charmander doesn't exist, not removing."); } } }
static void Main(string[] args) { string connectionString = SecretConfiguration.ConnectionString; DbContextOptions <PokemonDbContext> options = new DbContextOptionsBuilder <PokemonDbContext>() .UseSqlServer(connectionString) .UseLoggerFactory(AppLoggerFactory) .Options; using var context = new PokemonDbContext(options); DisplayPokemon(context); AddNewPokemon(context); EditAPokemon(context); DeleteAPokemon(context); }
public async Task Oracle() { const string ORACLE = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=xe)));User Id=system;Password=2e16b6823be300a9;"; //try //{ // await RoundHouseHelpers.ResetDatabaseOracle(new OracleConnection(ORACLE)); //} //catch (Exception ex) //{ // throw; //} var result = RoundHouseHelpers.MigrateOracle(@"C:\Users\devil\source\repos\DatabaseProviders\GettingStarted.AspNetCore.Api\Infrastructure\Persistence\Migrations\oracle", ORACLE, "pokemons-test", "roundhouse.databases.oracle"); var configuration = new ConfigurationBuilder().AddInMemoryCollection( new Dictionary <string, string> { { "ConnectionStrings:Pokemons", ORACLE }, } ).Build(); var options = new DbContextOptionsBuilder <PokemonDbContext>(); var mb = new ModelBuilder(new ConventionSet() { }).Model; options.UseOracle(ORACLE, a => { a.UseOracleSQLCompatibility("11"); }); options.EnableSensitiveDataLogging(); //options.UseModel(mb); var dbContext = new PokemonDbContext(options.Options); var repo = new PokemonsOracle(configuration, dbContext); //var pokemon = new Api.Domain.Pokemon //{ // Id = new Guid("1eb892bb-69a0-4677-b093-843f713fade9"), // Name = "paco" //}; //await repo.Create(pokemon); //await repo.SaveChangesAsync(); var data = await repo.GetPokemonsAsync(); await RoundHouseHelpers.ResetDatabase(new OracleConnection(ORACLE)); }
public IActionResult FireAndForget1([FromServices] PokemonDbContext context) { // This is an implicit async void method. ThreadPool.QueueUserWorkItem takes an Action, but the compiler allows // async void delegates to be used in its place. This is dangerous because unhandled exceptions will bring down the entire server process. ThreadPool.QueueUserWorkItem(async state => { await Task.Delay(1000); // This closure is capturing the context from the Controller action parameter. This is bad because this work item could run // outside of the request scope and the PokemonDbContext is scoped to the request. As a result, this will crash the process with // and ObjectDisposedException context.Pokemon.Add(new Pokemon()); await context.SaveChangesAsync(); }); return(Accepted()); }
public IActionResult FireAndForget2([FromServices] PokemonDbContext context) { // This uses Task.Run instead of ThreadPool.QueueUserWorkItem. It's mostly equivalent to the FireAndForget1 but since we're using // async Task instead of async void, unhandled exceptions won't crash the process. They will however trigger the TaskScheduler.UnobservedTaskException // event when exceptions go unhandled. Task.Run(async() => { await Task.Delay(1000); // This closure is capturing the context from the Controller action parameter. This is bad because this work item could run // outside of the request scope and the PokemonDbContext is scoped to the request. As a result, this will throw an unhandled ObjectDisposedException. context.Pokemon.Add(new Pokemon()); await context.SaveChangesAsync(); }); return(Accepted()); }
static void EditAPokemon(PokemonDbContext context) { // check if already exists var charmander = context.Pokemon.FirstOrDefault(p => p.Name == "Charmander"); // if this dbcontext instance is tracking any objects already, you will see them // connected to other objects even if you didn't not call include THAT time. if (charmander is null) { Console.WriteLine("Charmander does not exist; not editing"); return; } charmander.Height += 100; context.SaveChanges(); }
static void DeleteAPokemon(PokemonDbContext context) { // check if already exists var charmander = context.Pokemon.FirstOrDefault(p => p.Name == "charmander"); //IQueryable<int> queryableOfHeights = context.Pokemon.Where(p => p.Name.Length > 6).Select(p => p.Height); //// IQueryable also uses deferred execution -- no SQL commands have been executed yet //queryableOfHeights.ToList(); // if this dbcontext instance is tracking any objects already, you will see them // connected to other objects even if you didn't not call include THAT time. if (charmander is null) { Console.WriteLine("Charmander does not exist; not deleting"); return; } context.Pokemon.Remove(charmander); context.SaveChanges(); }
private static void EditSomePokemon(DbContextOptions <PokemonDbContext> options) { // in between dbcontext creation and each savechanges call is a transaction using (var dbContext = new PokemonDbContext(options)) { // EF "tracks" the objects you pull out of it. Pokemon charmander = dbContext.Pokemon.Include(x => x.Type) .First(x => x.Name == "Charmander"); Type grass = dbContext.Type.First(x => x.Name == "Grass"); Type fire = dbContext.Type.First(x => x.Name == "Fire"); if (charmander.Type == fire) { charmander.Type = grass; } else { charmander.Type = fire; } dbContext.SaveChanges(); } }
public PokemonController(PokemonDbContext dbContext) { _db = dbContext; }
public PokemonsController(PokemonDbContext db) { _db = db; }
public TrainersController(PokemonDbContext db) { _db = db; }
public AdminsRepositoryImpl(PokemonDbContext dbContext) { this.dbContext = dbContext; }
public StatsRepositoryImpl(PokemonDbContext dbContext) { this.dbContext = dbContext; }
static void DeleteAPokemon(PokemonDbContext context) { }
public PokemonController() { _pokemonDAL = new PokemonDAL(); _pokemonContext = new PokemonDbContext(); }
public HomeController(PokemonDbContext c) { _context = c; }
static void EditAPokemon(PokemonDbContext context) { }
public PokemonsOracle(IConfiguration configuration, PokemonDbContext pokemonDbContext) { _configuration = configuration; _pokemonDbContext = pokemonDbContext; }
public PokemonsController(PokemonDbContext context) { _context = context; }
public FavoritesController(PokemonDbContext pokemonDbContext) { _PokemonDB = pokemonDbContext; }
public JsonResult AllPokemon() { PokemonDbContext database = new PokemonDbContext(); return(Json(database.Pokemans.OrderBy(x => x.Name).ToList(), JsonRequestBehavior.AllowGet)); }
public PokemonRepository(PokemonDbContext _Db) { Db = _Db; DbSet = Db.Set <Pokemon>(); }