Example #1
0
        private static void ExplicitLoadQuotes()
        {
            var samurai = context.Samurais.FirstOrDefault(s => s.Name.Contains("Kikuchiyo"));

            // Load only works for a single object
            context.Entry(samurai).Collection(s => s.Quotes).Load();
            context.Entry(samurai).Reference(s => s.Horse).Load();

            /*
             * // Filter loaded data using 'Query'. This only results in one db execution.
             * // (Not possible with eager loading)
             * var happyQuotes = context.Entry(samurai)
             *      .Collection(b => b.Quotes)
             *      .Query()
             *      .Where(q => q.Text.Contains("save"))
             *      .ToList();
             */
        }
Example #2
0
        private static void ModifyingRelatedDataWhenNotTracked()
        {
            var samurai = context.Samurais.Include(s => s.Quotes).FirstOrDefault(s => s.Id == 19);
            var quote   = samurai.Quotes[0];

            quote.Text = "Did you hear that again?";

            using (var newContext = new SamuraiConsoleContext())
            {
                // Don't use this. It will update the parent samurai and all its quotes.
                // Don't use: newContext.Quotes.Update(quote);
                // ...use this instead. Will only modify the quote in the database.
                newContext.Entry(quote).State = EntityState.Modified;
                newContext.SaveChanges();
            }
        }
Example #3
0
        public void CanInsertSamuraiIntoDatabase()
        {
            var builder = new DbContextOptionsBuilder();

            // Passing a name so the db can be used elsewhere using 'UseInMemoryDatabase' again.
            builder.UseInMemoryDatabase("CanInsertSamurai");

            using (var context = new SamuraiConsoleContext(builder.Options))
            {
                // context.Database.EnsureDeleted(); // Takes long time
                // 'EnsureCreated' can be used to seed the database with the EF Core migrations
                // context.Database.EnsureCreated();
                var samurai = new Samurai();
                context.Samurais.Add(samurai);
                // Properties are non-nullable needs to be populated in advance, eg. the 'Name' field.
                // Because the InMemory database is used, the samurai already gets its id when using 'Add', not 'SaveChanges'
                // 'SaveChanges' only make sense when testing with a real databse.
                // Use 'Samurais.Count' to check if added or:
                Assert.AreEqual(EntityState.Added, context.Entry(samurai).State);
            }
        }