private async Task Can_use_connection_string_name_in_OnConfiguring_test(string connectionName)
        {
            var configuration = new Configuration
                {
                    new MemoryConfigurationSource(
                        new Dictionary<string, string>
                            {
                                { "Data:Northwind:ConnectionString", SqlServerTestDatabase.NorthwindConnectionString }
                            })
                };

            var serviceCollection = new ServiceCollection();
            serviceCollection
                .AddInstance<IConfiguration>(configuration)
                .AddEntityFramework()
                .AddSqlServer();

            var serviceProvider = serviceCollection.BuildServiceProvider();

            using (await SqlServerTestDatabase.Northwind())
            {
                using (var context = new NorthwindContext(serviceProvider, connectionName))
                {
                    Assert.Equal(91, await context.Customers.CountAsync());
                }
            }
        }
        private static async Task Can_use_an_existing_closed_connection_test(bool openConnection)
        {
            var serviceCollection = new ServiceCollection();
            serviceCollection
                .AddEntityFramework()
                .AddSqlServer();

            var serviceProvider = serviceCollection.BuildServiceProvider();

            using (var store = await SqlServerNorthwindContext.GetSharedStoreAsync())
            {
                var openCount = 0;
                var closeCount = 0;
                var disposeCount = 0;

                using (var connection = new SqlConnection(store.Connection.ConnectionString))
                {
                    if (openConnection)
                    {
                        await connection.OpenAsync();
                    }

                    connection.StateChange += (_, a) =>
                        {
                            if (a.CurrentState == ConnectionState.Open)
                            {
                                openCount++;
                            }
                            else if (a.CurrentState == ConnectionState.Closed)
                            {
                                closeCount++;
                            }
                        };
#if !DNXCORE50
                    connection.Disposed += (_, __) => disposeCount++;
#endif

                    using (var context = new NorthwindContext(serviceProvider, connection))
                    {
                        Assert.Equal(91, await context.Customers.CountAsync());
                    }

                    if (openConnection)
                    {
                        Assert.Equal(ConnectionState.Open, connection.State);
                        Assert.Equal(0, openCount);
                        Assert.Equal(0, closeCount);
                    }
                    else
                    {
                        Assert.Equal(ConnectionState.Closed, connection.State);
                        Assert.Equal(1, openCount);
                        Assert.Equal(1, closeCount);
                    }

                    Assert.Equal(0, disposeCount);
                }
            }
        }
 protected override void Setup()
 {
   session = CreateSession();
   db = new NorthwindContext(session);
   
   Customers = db.Customers.ToList();
   Employees = db.Employees.ToList();
   Orders = db.Orders.ToList();
   Products = db.Products.ToList();
 }
 public async Task Can_query_with_implicit_services_and_OnConfiguring()
 {
     using (await SqlServerNorthwindContext.GetSharedStoreAsync())
     {
         using (var context = new NorthwindContext())
         {
             Assert.Equal(91, await context.Customers.CountAsync());
         }
     }
 }
Exemplo n.º 5
0
        protected override void Setup()
        {
            db = new NorthwindContext();
          
            Customers = db.Customers.ToList();
            Employees = db.Employees.ToList();
            Orders = db.Orders.ToList();
            Products = db.Products.ToList();

            // DbContextLogging.LogToTrace(db);
        }
            public async Task Can_query_with_implicit_services_and_explicit_config()
            {
                using (await SqlServerTestDatabase.Northwind())
                {
                    var options = new DbContextOptions().UseSqlServer(SqlServerTestDatabase.NorthwindConnectionString);

                    using (var context = new NorthwindContext(options))
                    {
                        Assert.Equal(91, await context.Customers.CountAsync());
                    }
                }
            }
 public async Task Can_query_with_implicit_services_and_explicit_config()
 {
     using (SqlServerNorthwindContext.GetSharedStore())
     {
         using (var context = new NorthwindContext(
             new DbContextOptionsBuilder()
                 .UseSqlServer(SqlServerNorthwindContext.ConnectionString).Options))
         {
             Assert.Equal(91, await context.Customers.CountAsync());
         }
     }
 }
        private static void SelectEmployeeForTenants(NorthwindContext context)
        {
            context.SetTenantId(tenant1Id);

            var tenant1Employees = context.Employees.ToList();
            Console.WriteLine($"Tenant 1 has {tenant1Employees.Count} employees");

            context.SetTenantId(tenant2Id);

            var tenant2Employees = context.Employees.ToList();
            Console.WriteLine($"Tenant 2 has {tenant2Employees.Count} employees");
        }
 private async Task AddChuckNorrisToMyTenant(NorthwindContext context)
 {
     if (!context.Employees.Any(e => e.FirstName == "Chuck" && e.LastName == "Norris"))
     {
         //Example of adding employee to tenant 
         var chuck = new Employee();
         chuck.FirstName = "Chuck";
         chuck.LastName = "Norris";
         chuck.Address = "Everywhere";
         chuck.EmployeeId = new Random().Next();
         context.Employees.Add(chuck);
         await context.SaveChangesAsync();
     }
 }
 public async Task Can_query_with_explicit_services_and_OnConfiguring()
 {
     using (SqlServerNorthwindContext.GetSharedStore())
     {
         using (var context = new NorthwindContext(
             new DbContextOptionsBuilder().UseInternalServiceProvider(
                 new ServiceCollection()
                     .AddEntityFrameworkSqlServer()
                     .BuildServiceProvider()).Options))
         {
             Assert.Equal(91, await context.Customers.CountAsync());
         }
     }
 }
        public void Northwind_SimpleDynamicSelectMatchesNormalSelect()
        {
            using (var connection = Effort.DbConnectionFactory.CreateTransient())
            using (var context = new NorthwindContext(connection, contextOwnsConnection: true))
            {
                var dynamicSelectQueryable = new QueryableDynamicSelector().SelectProperties(context.Customers, new HashSet<string> { "CustomerID", "ContactName" });
                var dynamicSelectSql = dynamicSelectQueryable.ToString();

                var normalSelectQueryable = context.Customers.Select(c => new { c.CustomerID, c.ContactName });
                var normalSelectSql = normalSelectQueryable.ToString();

                Assert.AreEqual(normalSelectSql, dynamicSelectSql);
            }
        }
        private static void CreateTenantEmployee(NorthwindContext context, Guid tenant)
        {
            context.SetTenantId(tenant);

            //Adding employee to tenant
            var chuck = new Employee();
            chuck.FirstName = "Chuck";
            chuck.LastName = "Norris";
            chuck.Address = "Everywhere";
            chuck.EmployeeId = new Random().Next();
            context.Employees.Add(chuck);
            context.SaveChanges();


        }
Exemplo n.º 13
0
        public async Task Can_use_actual_connection_string_in_OnConfiguring()
        {
            var serviceCollection = new ServiceCollection();
            serviceCollection
                .AddEntityFramework()
                .AddSqlServer();

            var serviceProvider = serviceCollection.BuildServiceProvider();

            using (await SqlServerNorthwindContext.GetSharedStoreAsync())
            {
                using (var context = new NorthwindContext(serviceProvider, SqlServerNorthwindContext.ConnectionString))
                {
                    Assert.Equal(91, await context.Customers.CountAsync());
                }
            }
        }
Exemplo n.º 14
0
		protected void Application_Start()
		{
			AreaRegistration.RegisterAllAreas();

			RegisterGlobalFilters(GlobalFilters.Filters);
			RegisterRoutes(RouteTable.Routes);

			DbProviderFactoryBase.RegisterProvider<CachingProviderFactory>();
			DbConfiguration.SetConfiguration(new CachedDbConfiguration(CacheWithStatistics));

			using (var context = new NorthwindContext("Northwind"))
			{
				context.Database.CreateIfNotExists();
			}

			BootstrapContainer();

			////new NorthwindContext("Northwind").Database.CreateIfNotExists();
		}
        public async Task<ActionResult> Index()
        {
            // Only needed on first load of application to add demo users
            await CreateDemoUsersIfNeeded();

            // once the user is logged in, add chuck norris and get listing of employees
            if (User.Identity.IsAuthenticated)
            {
                var context = new NorthwindContext();

                // only adds chuck if he isn't there already for the current user's tenant
                await AddChuckNorrisToMyTenant(context);

                // get list of employees for this tenant
                ViewBag.Employees = context.Employees.ToList();
            }

            return View();
        }
        static void Main(string[] args)
        {
            //Restore northwind.bak and change your connection settings in the app.config file.

            //Database include two tenants (dbo.Tenant)
            //F06FE619-21CC-E511-8113-005056BE3E20 Tenant 1
            //F16FE619-21CC-E511-8113-005056BE3E20 Tenant 2

            //Database already has some employees assigned to tenant 1 and tenant 2
            var context = new NorthwindContext();

            SelectEmployeeForTenants(context);

            Console.WriteLine("Creating employee for tenant 1");
            CreateTenantEmployee(context,tenant1Id);

            SelectEmployeeForTenants(context);


            Console.ReadLine();

        }
Exemplo n.º 17
0
 public ProductService(NorthwindContext db)
 {
     _db = db;
 }
 public async Task Throws_on_attempt_to_use_context_with_no_store()
 {
     using (await SqlServerNorthwindContext.GetSharedStoreAsync())
     {
         Assert.Equal(
             CoreStrings.NoDataStoreConfigured,
             Assert.Throws<InvalidOperationException>(() =>
                 {
                     using (var context = new NorthwindContext())
                     {
                         Assert.Equal(91, context.Customers.Count());
                     }
                 }).Message);
     }
 }
            public void Throws_on_attempt_to_use_SQL_Server_without_providing_connection_string()
            {
                using (SqlServerNorthwindContext.GetSharedStore())
                {
                    var serviceCollection = new ServiceCollection();
                    serviceCollection
                        .AddEntityFramework()
                        .AddSqlServer();

                    var serviceProvider = serviceCollection.BuildServiceProvider();

                    Assert.Equal(
                        CoreStrings.NoProviderConfigured,
                        Assert.Throws<InvalidOperationException>(() =>
                            {
                                using (var context = new NorthwindContext(serviceProvider))
                                {
                                    Assert.Equal(91, context.Customers.Count());
                                }
                            }).Message);
                }
            }
Exemplo n.º 20
0
 public AuthenticationController(UserManager <ApplicationUser> userManager, RoleManager <IdentityRole> roleManager, IConfiguration configuration, NorthwindContext dbContext, ApplicationDbContext idContext) : base()
 {
     this._userManager = userManager;
     this._roleManager = roleManager;
     _configuration    = configuration;
     nwContext         = dbContext;
     appContext        = idContext;
 }
Exemplo n.º 21
0
        public static void Main(string[] args)
        {
            var db = new NorthwindContext();

            logger.Info("Program started");
            try
            {
                string choice;
                do
                {
                    Console.WriteLine("1) Display Categories");
                    Console.WriteLine("2) Add Category");
                    Console.WriteLine("3) Display Category and related products");
                    Console.WriteLine("4) Display all Categories and their related products");
                    Console.WriteLine("\"q\" to quit");
                    choice = Console.ReadLine();
                    Console.Clear();
                    logger.Info($"Option {choice} selected");
                    if (choice == "1")
                    {
                        var query = db.Categories.OrderBy(p => p.CategoryName);

                        Console.WriteLine($"{query.Count()} records returned");
                        foreach (var item in query)
                        {
                            Console.WriteLine($"{item.CategoryName} - {item.Description}");
                        }
                    }
                    else if (choice == "2")
                    {
                        Category category = new Category();
                        Console.WriteLine("Enter Category Name:");
                        category.CategoryName = Console.ReadLine();
                        Console.WriteLine("Enter the Category Description:");
                        category.Description = Console.ReadLine();

                        ValidationContext       context = new ValidationContext(category, null, null);
                        List <ValidationResult> results = new List <ValidationResult>();

                        var isValid = Validator.TryValidateObject(category, context, results, true);
                        if (isValid)
                        {
                            // check for unique name
                            if (db.Categories.Any(c => c.CategoryName == category.CategoryName))
                            {
                                // generate validation error
                                isValid = false;
                                results.Add(new ValidationResult("Name exists", new string[] { "CategoryName" }));
                            }
                            else
                            {
                                logger.Info("Validation passed");
                                // TODO: save category to db
                                db.AddCategory(category);
                                logger.Info("Category added - {name}", category.CategoryName);
                            }
                        }
                        if (!isValid)
                        {
                            foreach (var result in results)
                            {
                                logger.Error($"{result.MemberNames.First()} : {result.ErrorMessage}");
                            }
                        }
                    }
                    else if (choice == "3")
                    {
                        var query = db.Categories.OrderBy(p => p.CategoryId);

                        Console.WriteLine("Select the category whose products you want to display:");
                        foreach (var item in query)
                        {
                            Console.WriteLine($"{item.CategoryId}) {item.CategoryName}");
                        }
                        int id = int.Parse(Console.ReadLine());
                        Console.Clear();
                        logger.Info($"CategoryId {id} selected");
                        Category category = db.Categories.FirstOrDefault(c => c.CategoryId == id);
                        Console.WriteLine($"{category.CategoryName} - {category.Description}");
                        foreach (Product p in category.Products)
                        {
                            Console.WriteLine(p.ProductName);
                        }
                    }
                    else if (choice == "4")
                    {
                        var query = db.Categories.Include("Products").OrderBy(p => p.CategoryId);
                        foreach (var item in query)
                        {
                            Console.WriteLine($"{item.CategoryName}");
                            foreach (Product p in item.Products)
                            {
                                Console.WriteLine($"\t{p.ProductName}");
                            }
                        }
                    }
                    Console.WriteLine();
                } while (choice.ToLower() != "q");
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }
            logger.Info("Program ended");
        }
Exemplo n.º 22
0
        public static void Main(string[] args)
        {
            logger.Info("Program started");
            try
            {
                string choice;
                do
                {
                    Console.Clear();
                    Console.WriteLine("1) Add a Product");
                    Console.WriteLine("2) Display all Products");
                    Console.WriteLine("3) Display Active Products");
                    Console.WriteLine("4) Display Discontinued Products");
                    Console.WriteLine("5) Search Products");
                    Console.WriteLine("6) Add a  Category");
                    Console.WriteLine("7) Edit a  Category");
                    Console.WriteLine("8) Display all Categories");
                    Console.WriteLine("9) Display all non-discontinued items by Category");
                    Console.WriteLine("10) Display all non-discontinued items by specific Category");
                    Console.WriteLine("11) Delete a Category");
                    Console.WriteLine("12) Delete a  Product");
                    Console.WriteLine(" Enter the \"q\" button to quit");
                    choice = Console.ReadLine();

                    switch (choice)
                    {
                    case "1":
                        Product.addProducts(logger);
                        break;

                    case "2":
                        Product.displayAllProducts(logger);
                        break;

                    case "3":
                        Product.displayActiveProducts(logger);
                        break;

                    case "4":
                        Product.displayDiscontinuedProducts(logger);
                        break;

                    case "5":
                        Product.searchProducts(logger);
                        break;

                    case "6":
                        Category.addCategories(logger);
                        break;

                    case "7":

                        var db = new NorthwindContext();

                        Console.WriteLine("Choose category ID to edit: ");

                        var category = Category.GetCategory(db, logger);


                        if (category != null)
                        {
                            Category UpdatedCategory = Category.InputCategory(db, logger);

                            if (UpdatedCategory != null)
                            {
                                UpdatedCategory.CategoryId = category.CategoryId;
                                db.EditCategory(UpdatedCategory);
                                logger.Info($"Category Id: {UpdatedCategory.CategoryId} updated");
                            }
                        }

                        Console.WriteLine();
                        Console.WriteLine("Press any key to return to menu");
                        Console.ReadLine();
                        break;

                    case "8":
                        Category.displayAllCategories(logger);
                        break;

                    case "9":
                        Category.displayAllCategoriesAndProductsNotDiscontinued(logger);
                        break;

                    case "10":
                        Category.displaySpecificCategoryAndProducts(logger);
                        break;

                    case "11":
                        db = new NorthwindContext();
                        Console.WriteLine("Select category ID to delete:");
                        var categoryToDelete = Category.GetCategory(db, logger);
                        try
                        {
                            db.deleteCategory(categoryToDelete);
                            logger.Info($"{categoryToDelete.CategoryName} deleted");
                        }
                        catch (Exception)
                        {
                            logger.Error("Cannot Delete a record that affects other tables");
                        }



                        Console.WriteLine();
                        Console.WriteLine("Press any key to return to menu");
                        Console.ReadLine();

                        break;

                    case "12":
                        db = new NorthwindContext();
                        Console.WriteLine("Select product ID to delete:");
                        var productToDelete = Product.GetProduct(db, logger);
                        try
                        {
                            db.deleteProduct(productToDelete);
                            logger.Info($"{productToDelete.ProductName} deleted");
                        }
                        catch (Exception)
                        {
                            logger.Error("Cannot Delete a record that affects other tables");
                        }



                        Console.WriteLine();
                        Console.WriteLine("Press any key to return to menu");
                        Console.ReadLine();

                        break;

                    default:
                        logger.Info("No option chosen");
                        break;
                    }
                } while (choice.ToLower() != "q");
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }
            logger.Info("Program ended");
        }
                public MyController(NorthwindContext context)
                {
                    Assert.NotNull(context);

                    _context = context;
                }
 public SuppliersApiController(NorthwindContext context)
 {
     _context = context;
 }
Exemplo n.º 25
0
 public CustomersController(NorthwindContext northwindContext)
 {
     _northwindContext = northwindContext;
 }
Exemplo n.º 26
0
 public GenericRepository(NorthwindContext dbContext)
 {
     _dbContext = dbContext;
 }
Exemplo n.º 27
0
        public void CreateOrderObjectGraphTest()
        {
            using (IDataContextAsync context = new NorthwindContext())
                using (IUnitOfWorkAsync unitOfWork = new UnitOfWork(context))
                {
                    IRepositoryAsync <Order> orderRepository = new Repository <Order>(context, unitOfWork);

                    var orderTest = new Order
                    {
                        CustomerID  = "LLE39",
                        EmployeeID  = 10,
                        OrderDate   = DateTime.Now,
                        ObjectState = ObjectState.Added,

                        Employee = new Employee
                        {
                            EmployeeID  = 10,
                            FirstName   = "Test",
                            LastName    = "Le",
                            ObjectState = ObjectState.Added
                        },

                        OrderDetails = new List <OrderDetail>
                        {
                            new OrderDetail
                            {
                                ProductID   = 1,
                                Quantity    = 5,
                                ObjectState = ObjectState.Added
                            },
                            new OrderDetail
                            {
                                ProductID   = 2,
                                Quantity    = 5,
                                ObjectState = ObjectState.Added
                            }
                        }
                    };

                    orderRepository.InsertOrUpdateGraph(orderTest);

                    try
                    {
                        unitOfWork.SaveChanges();
                    }
                    catch (DbEntityValidationException ex)
                    {
                        var sb = new StringBuilder();

                        foreach (var failure in ex.EntityValidationErrors)
                        {
                            sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType());

                            foreach (var error in failure.ValidationErrors)
                            {
                                sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
                                sb.AppendLine();
                            }
                        }

                        Debug.WriteLine(sb.ToString());
                        TestContext.WriteLine(sb.ToString());
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                        TestContext.WriteLine(ex.Message);
                    }
                }
        }
Exemplo n.º 28
0
 public HomeController(NorthwindContext db) => _northwindContext = db;
Exemplo n.º 29
0
 public EmployeesController(NorthwindContext context)
 {
     _context = context;
 }
Exemplo n.º 30
0
 public CreateModel(NorthwindContext context, CountryService countryService)
 {
     _context           = context;
     AvailableCountries = countryService.GetCountries();
 }
 public UpdateProductCommandHandler(NorthwindContext context)
 {
     _context = context;
 }
 public async Task Can_pass_connection_string_to_constructor_and_use_in_OnConfiguring()
 {
     using (await SqlServerNorthwindContext.GetSharedStoreAsync())
     {
         using (var context = new NorthwindContext(SqlServerNorthwindContext.ConnectionString))
         {
             Assert.Equal(91, await context.Customers.CountAsync());
         }
     }
 }
Exemplo n.º 33
0
 public GenericRepository(NorthwindContext context)
 {
     db = context;
 }
            public async Task Can_query_with_explicit_services_and_OnConfiguring()
            {
                using (await SqlServerNorthwindContext.GetSharedStoreAsync())
                {
                    var serviceCollection = new ServiceCollection();
                    serviceCollection
                        .AddEntityFramework()
                        .AddSqlServer();

                    var serviceProvider = serviceCollection.BuildServiceProvider();

                    using (var context = new NorthwindContext(serviceProvider))
                    {
                        Assert.Equal(91, await context.Customers.CountAsync());
                    }
                }
            }
Exemplo n.º 35
0
 public CategoriesController(NorthwindContext context)
 {
     _context = context;
 }
Exemplo n.º 36
0
                public MyController(NorthwindContext context)
                {
                    Assert.NotNull(context);

                    _context = context;
                }
Exemplo n.º 37
0
 public OrderRepository(NorthwindContext context)
     : base(context)
 {
 }
Exemplo n.º 38
0
 public DataRepository(NorthwindContext northwindContext)
 {
     this.northwindContext = northwindContext;
 }
            public async Task Can_query_with_explicit_services_and_explicit_config()
            {
                using (SqlServerNorthwindContext.GetSharedStore())
                {
                    var serviceCollection = new ServiceCollection();
                    serviceCollection
                        .AddEntityFramework()
                        .AddSqlServer();

                    var serviceProvider = serviceCollection.BuildServiceProvider();

                    var optionsBuilder = new DbContextOptionsBuilder();
                    optionsBuilder.UseSqlServer(SqlServerNorthwindContext.ConnectionString);

                    using (var context = new NorthwindContext(serviceProvider, optionsBuilder.Options))
                    {
                        Assert.Equal(91, await context.Customers.CountAsync());
                    }
                }
            }
 public CustomerDemographicsRepository(NorthwindContext context)
 {
     _context = context;
 }
Exemplo n.º 41
0
 public CustomersController(NorthwindContext context)
 {
     _context = context;
 }
 public void Throws_on_attempt_to_use_store_with_no_store_services()
 {
     using (SqlServerNorthwindContext.GetSharedStore())
     {
         Assert.Equal(
             CoreStrings.NoProviderConfigured,
             Assert.Throws<InvalidOperationException>(() =>
                 {
                     using (var context = new NorthwindContext(
                         new DbContextOptionsBuilder()
                             .UseInternalServiceProvider(new ServiceCollection()
                                 .AddEntityFramework()
                                 .BuildServiceProvider()).Options))
                     {
                         Assert.Equal(91, context.Customers.Count());
                     }
                 }).Message);
     }
 }
            public async Task Throws_on_attempt_to_use_store_with_no_store_services()
            {
                using (await SqlServerNorthwindContext.GetSharedStoreAsync())
                {
                    var serviceCollection = new ServiceCollection();
                    serviceCollection
                        .AddEntityFramework();

                    var serviceProvider = serviceCollection.BuildServiceProvider();

                    Assert.Equal(
                        CoreStrings.NoDataStoreService,
                        Assert.Throws<InvalidOperationException>(() =>
                            {
                                using (var context = new NorthwindContext(serviceProvider))
                                {
                                    Assert.Equal(91, context.Customers.Count());
                                }
                            }).Message);
                }
            }
Exemplo n.º 44
0
 public RegionService(NorthwindContext db)
 {
     _db = db;
 }
            public async Task Can_pass_context_options_to_constructor_and_use_in_builder()
            {
                using (await SqlServerNorthwindContext.GetSharedStoreAsync())
                {
                    var optionsBuilder = new DbContextOptionsBuilder();
                    optionsBuilder.UseSqlServer(SqlServerNorthwindContext.ConnectionString);

                    using (var context = new NorthwindContext(optionsBuilder.Options))
                    {
                        Assert.Equal(91, await context.Customers.CountAsync());
                    }
                }
            }
 public async Task Throws_on_attempt_to_use_context_with_no_store()
 {
     using (await SqlServerTestDatabase.Northwind())
     {
         Assert.Equal(
             GetString("FormatNoDataStoreConfigured"),
             Assert.Throws<DataStoreException>(() =>
                 {
                     using (var context = new NorthwindContext())
                     {
                         Assert.Equal(91, context.Customers.Count());
                     }
                 }).InnerException.Message);
     }
 }
            public async Task Can_use_one_context_nested_inside_another_of_the_same_type()
            {
                using (await SqlServerNorthwindContext.GetSharedStoreAsync())
                {
                    var serviceCollection = new ServiceCollection();
                    serviceCollection
                        .AddEntityFramework()
                        .AddSqlServer();

                    var serviceProvider = serviceCollection.BuildServiceProvider();

                    using (var context1 = new NorthwindContext(serviceProvider))
                    {
                        var customers1 = await context1.Customers.ToListAsync();
                        Assert.Equal(91, customers1.Count);
                        Assert.Equal(91, context1.ChangeTracker.Entries().Count());

                        using (var context2 = new NorthwindContext(serviceProvider))
                        {
                            Assert.Equal(0, context2.ChangeTracker.Entries().Count());

                            var customers2 = await context2.Customers.ToListAsync();
                            Assert.Equal(91, customers2.Count);
                            Assert.Equal(91, context2.ChangeTracker.Entries().Count());

                            Assert.Equal(customers1[0].CustomerID, customers2[0].CustomerID);
                            Assert.NotSame(customers1[0], customers2[0]);
                        }
                    }
                }
            }
            public async Task Throws_on_attempt_to_use_store_with_no_store_services()
            {
                using (await SqlServerTestDatabase.Northwind())
                {
                    var serviceCollection = new ServiceCollection();
                    serviceCollection.AddEntityFramework();
                    var serviceProvider = serviceCollection.BuildServiceProvider();

                    Assert.Equal(
                        GetString("FormatNoDataStoreService"),
                        Assert.Throws<DataStoreException>(() =>
                            {
                                using (var context = new NorthwindContext(serviceProvider))
                                {
                                    Assert.Equal(91, context.Customers.Count());
                                }
                            }).InnerException.Message);
                }
            }
 public async Task Can_pass_connection_string_to_constructor_and_use_in_OnConfiguring()
 {
     using (await SqlServerTestDatabase.Northwind())
     {
         using (var context = new NorthwindContext(SqlServerTestDatabase.NorthwindConnectionString))
         {
             Assert.Equal(91, await QueryableExtensions.CountAsync(context.Customers));
         }
     }
 }
Exemplo n.º 50
0
        public void InsertProducts()
        {
            using (IDataContextAsync context = new NorthwindContext())
                using (IUnitOfWorkAsync unitOfWork = new UnitOfWork(context))
                {
                    IRepositoryAsync <Product> productRepository = new Repository <Product>(context, unitOfWork);

                    var newProducts = new[]
                    {
                        new Product {
                            ProductName = "One", Discontinued = false, TrackingState = TrackingState.Added
                        },
                        new Product {
                            ProductName = "12345678901234567890123456789012345678901234567890", Discontinued = true, TrackingState = TrackingState.Added
                        },
                        new Product {
                            ProductName = "Three", Discontinued = true, TrackingState = TrackingState.Added
                        },
                        new Product {
                            ProductName = "Four", Discontinued = true, TrackingState = TrackingState.Added
                        },
                        new Product {
                            ProductName = "Five", Discontinued = true, TrackingState = TrackingState.Added
                        }
                    };

                    foreach (var product in newProducts)
                    {
                        try
                        {
                            productRepository.Insert(product);
                            unitOfWork.SaveChanges();
                        }
                        catch (DbEntityValidationException ex)
                        {
                            var sb = new StringBuilder();

                            foreach (var failure in ex.EntityValidationErrors)
                            {
                                sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType());

                                foreach (var error in failure.ValidationErrors)
                                {
                                    sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
                                    sb.AppendLine();
                                }
                            }

                            Debug.WriteLine(sb.ToString());
                            TestContext.WriteLine(sb.ToString());
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine(ex.Message);
                            TestContext.WriteLine(ex.Message);
                        }
                    }

                    var insertedProduct = productRepository.Query(x => x.ProductName == "One").Select().FirstOrDefault();
                    Assert.IsTrue(insertedProduct?.ProductName == "One");
                }
        }