public IReadOnlyList <T> FindMany <T>(Expression <Func <T, bool> > filter) where T : class { using (var context = new EntityFrameworkDbContext()) { return(context.Set <T>().Where(filter).ToList()); } }
public T QueryOne <T>(Expression <Func <T, bool> > filter) where T : class { using (var context = new EntityFrameworkDbContext()) { return(context.Set <T>().SingleOrDefault(filter)); } }
public TEntity Add(TEntity entity) { entity.Created = DateTime.UtcNow; TEntity addedEntity = DbSet.Add(entity); EntityFrameworkDbContext.SaveChanges(); return(addedEntity); }
public void InserMany <T>(IEnumerable <T> entities) where T : class { using (var context = new EntityFrameworkDbContext()) { context.Set <T>().AddRange(entities); context.SaveChanges(); } }
public void InsertOne <T>(T entity) where T : class { using (var context = new EntityFrameworkDbContext()) { context.Set <T>().Add(entity); context.SaveChanges(); } }
public async Task <IActionResult> Index() { using (var context = new EntityFrameworkDbContext()) { var model = await context.Authors.AsNoTracking().ToListAsync(); return(View(model)); } }
public virtual void Update(TEntity entity, bool save = true) { DbSet.Attach(entity); EntityFrameworkDbContext.Entry(entity).State = EntityState.Modified; if (save) { EntityFrameworkDbContext.SaveChanges(); } }
public async Task <IActionResult> Create([Bind("FirstName, LastName")] Author author) { using (var context = new EntityFrameworkDbContext()) { context.Add(author); await context.SaveChangesAsync(); return(RedirectToAction("Index")); } }
public async Task <IActionResult> Create([Bind("Title, AuthorId")] Book book) { using (var context = new EntityFrameworkDbContext()) { context.Books.Add(book); await context.SaveChangesAsync(); return(RedirectToAction("Index")); } }
private static void CreateFtpUsers(int count, string login) { using var context = new EntityFrameworkDbContext(); context.FtpUsers.AddRange(Enumerable.Range(0, count).Select(_ => new FtpUser { Login = login, BoxId = Guid.NewGuid().ToString(), Id = Guid.NewGuid(), })); context.SaveChanges(); }
private static UsersTable[] GenerateRandomUsersAndAssertCount(int count) { var scopeId = Guid.NewGuid().ToString(); var users = Enumerable.Range(0, count).Select(_ => GetRandomUser(scopeId, $"{Guid.NewGuid()}@gmail.com")).ToArray(); using var context = new EntityFrameworkDbContext(); context.Users.AddRange(users); context.SaveChanges(); Assert.That(() => GetUserObjectsCount(scopeId, count), Is.EqualTo(count).After(180000, 1000)); return(users); }
public async Task <IActionResult> Create() { using (var context = new EntityFrameworkDbContext()) { var authors = await context.Authors.Select(a => new SelectListItem { Value = a.AuthorId.ToString(), Text = $"{a.FirstName} {a.LastName}" }).ToListAsync(); ViewBag.Authors = authors; } return(View()); }
private static void TextMethod() { using (var db = new EntityFrameworkDbContext()) { var user = db.Users.First(name => name.NickName == "Marcello"); foreach (var friend in user.RequestedFriendships) { Console.WriteLine(user == friend.User1 ? friend.User2.NickName : friend.User1.NickName); } Console.WriteLine("_____________________________________________________"); foreach (var friend in user.AcceptedFriendships) { Console.WriteLine(user == friend.User1 ? friend.User2.NickName : friend.User1.NickName); } } }
private FtpUser CreateFtpUser() { using var context = new EntityFrameworkDbContext(); var userId = Guid.NewGuid(); var ftpUser = new FtpUser { Login = Guid.NewGuid().ToString(), BoxId = Guid.NewGuid().ToString(), Id = userId, }; context.FtpUsers.Add(ftpUser); context.SaveChanges(); Assert.That(GetFtpUser(userId), Is.Not.Null, "Failed to create ftp user"); return(ftpUser); }
public void TestAllowSort() { using (var context = new EntityFrameworkDbContext()) { var serializer = new Serializer(new AllPropertiesExtractor()); var customer = new Customer { Age = 1, Name = "13" }; context.Tests.Add(new TestTable { Id = 1, CompositeKey = Guid.NewGuid().ToString(), String = "123", Customer = customer, CustomerSerialized = serializer.Serialize(customer), }); context.Users.Add(new UsersTable { Email = "123", Id = Guid.NewGuid(), Patronymic = "1", Surname = "2", FirstName = "3", ScopeId = "scopeId", }); context.SaveChanges(); } using var browser = new BrowserForTests(); var usersPage = browser.LoginAsSuperUser().SwitchTo <BusinessObjectTablePage>("UsersTable"); usersPage = browser.RefreshUntil(usersPage, x => x.BusinessObjectItems.IsPresent.Get()); usersPage.TableHeader.WaitPresence(); usersPage.TableHeader.SortByColumn("Header_Id"); var largeObjectPage = browser.SwitchTo <BusinessObjectTablePage>("TestTable"); largeObjectPage = browser.RefreshUntil(largeObjectPage, x => x.BusinessObjectItems.IsPresent.Get()); largeObjectPage.TableHeader.WaitPresence(); largeObjectPage.TableHeader.WaitNotSortable("Header_Index"); largeObjectPage.TableHeader.WaitNotSortable("Header_String"); largeObjectPage.TableHeader.WaitNotSortable("Header_DateTime"); }
public void Test_DoubleTest_InsertToDatabase() { var configuration = new EntitySetupConfiguration(); // const string connectionString = "Data Source=(local); Database=easyERP_test; User ID=sa; Password=; MultipleActiveResultSets=True"; // EntityFrameworkDbContext dbContext = new EntityFrameworkDbContext(connectionString, configuration); // DbConnection dbConnection = new SqlConnection(); var dbContext = new EntityFrameworkDbContext("easyERP_test"); IUnitOfWork unitOfWork = new EntityFrameworkUnitOfWork(dbContext); var testRepository = new EntityFrameworkRepository <TestDoubles>(dbContext, unitOfWork); var testModel = new TestDoubles { Name = "test description" }; testRepository.Add(testModel); unitOfWork.Commit(); }
private static void CreateUsers(int count, string scopeId, Guid?id = null) { if (count > 1 && id != null) { throw new InvalidOperationException(); } using var context = new EntityFrameworkDbContext(); context.Users.AddRange(Enumerable.Range(0, count).Select(_ => new UsersTable { Id = id ?? Guid.NewGuid(), ScopeId = scopeId, Email = "*****@*****.**", FirstName = "1", Surname = "2", Patronymic = "3", })); context.SaveChanges(); }
public async Task Test() { var serializer = new Serializer(new AllPropertiesExtractor()); var customer = new Customer { Age = 1, Name = "qwer", Orders = new[] { new Order { Price = 3, ShippingAddress = "4" }, new Order { Price = 1, ShippingAddress = "2" }, } }; await using var context = new EntityFrameworkDbContext(); await context.Set <TestTable>().AddAsync(new TestTable { Id = 1, CompositeKey = "2", Boolean = false, Integer = 1345, String = "qwerty", DateTime = DateTime.Today, DateTimeOffset = DateTimeOffset.UtcNow, Customer = customer, CustomerSerialized = serializer.Serialize(customer), }); await context.Set <UsersTable>().AddAsync(new UsersTable { Id = 1, Email = "2", Name = "3", }); await context.SaveChangesAsync(); }
public int UpdatePricesInMainCurrency() { Currency mainCurrency = EntityFrameworkDbContext.Currencies.SingleOrDefault(x => !x.IsDeleted && x.IsMain); if (mainCurrency == null) { throw new ArgumentNullException("There is no main currency in the system!"); } var productsWithCurrencyRate = from product in DbSet join cr in (from currencyRate in EntityFrameworkDbContext.CurrencyRates where currencyRate.DateOfRate == (from currencyRate1 in EntityFrameworkDbContext.CurrencyRates select currencyRate1).Max(currencyRate1 => currencyRate1.DateOfRate) select currencyRate) on product.CurrencyIdOfThePrice equals cr.CurrencyId select new { Product = product, CurrencyRate = cr }; productsWithCurrencyRate.ToList().ForEach(x => { x.Product.PriceInTheMainCurrency = x.Product.Price * x.CurrencyRate.Rate; Update(x.Product, false); }); return(EntityFrameworkDbContext.SaveChanges()); }
public int UserInfoUpdate(UserInfoRequestModel request) { EntityFrameworkDbContext _db = new EntityFrameworkDbContext(); //修改需要对主键赋值,注意:这里需要对所有字段赋值,没有赋值的字段会用NULL更新到数据库 var user = new UserInfoResponseModel { UID = request.UID, UserNO = request.UserNO, UserName = request.UserName, UserEmail = request.UserEmail, PassWord = request.NewPassWord }; //将实体附加到对象管理器中 _db.UserInfo.Attach(user); //获取到状态实体,可以修改其状态 var setEntry = ((IObjectContextAdapter)_db).ObjectContext.ObjectStateManager.GetObjectStateEntry(user); //只修改实体属性 setEntry.SetModifiedProperty("PassWord"); return(_db.SaveChanges()); }
public IQueryable <TEntity> Get(Expression <Func <TEntity, bool> > filter = null, Func <IQueryable <TEntity>, IOrderedQueryable <TEntity> > orderBy = null, string includeProperties = "") { IQueryable <TEntity> query = EntityFrameworkDbContext.Set <TEntity>(); if (filter != null) { query = query.Where(filter); } if (!string.IsNullOrWhiteSpace(includeProperties)) { foreach (var includeProperty in includeProperties.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { query = query.Include(includeProperty); } } if (orderBy != null) { return(orderBy(query).AsQueryable()); } return(query.AsQueryable()); }
public OrdersRepository(EntityFrameworkDbContext entityFrameworkDbContext) : base(entityFrameworkDbContext) { }
public CountriesRepository(EntityFrameworkDbContext entityFrameworkDbContext) : base(entityFrameworkDbContext) { }
private static int GetUserObjectsCount(string scopeId, int limit) { using var context = new EntityFrameworkDbContext(); return(context.Users.Where(x => x.ScopeId == scopeId).Take(limit + 1).Count()); }
public virtual void Delete(params TEntity[] entities) { DbSet.RemoveRange(entities); EntityFrameworkDbContext.SaveChanges(); }
public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder) { //HTTP context and other related stuff builder.Register(c => new HttpContextWrapper(HttpContext.Current) as HttpContextBase) .As <HttpContextBase>() .InstancePerLifetimeScope(); builder.Register(c => c.Resolve <HttpContextBase>().Request) .As <HttpRequestBase>() .InstancePerLifetimeScope(); builder.Register(c => c.Resolve <HttpContextBase>().Response) .As <HttpResponseBase>() .InstancePerLifetimeScope(); builder.Register(c => c.Resolve <HttpContextBase>().Server) .As <HttpServerUtilityBase>() .InstancePerLifetimeScope(); builder.Register(c => c.Resolve <HttpContextBase>().Session) .As <HttpSessionStateBase>() .InstancePerLifetimeScope(); builder.RegisterInstance(new AreaSettings()).AsSelf(); //web helper builder.RegisterType <WebHelper>().As <IWebHelper>().InstancePerLifetimeScope(); //user agent helper builder.RegisterType <UserAgentHelper>().As <IUserAgentHelper>().InstancePerLifetimeScope(); //controllers builder.RegisterControllers(typeFinder.GetAssemblies().ToArray()); //data layer const string ConnectionString = "easyerp_db"; var dataContext = new EntityFrameworkDbContext(ConnectionString); builder.Register(d => new EntityFrameworkDbContext("easyerp_db")).AsSelf().As <IEntityFrameworkDbContext>() .InstancePerLifetimeScope(); builder.RegisterType <EntityFrameworkUnitOfWork>().As <IUnitOfWork>().InstancePerLifetimeScope(); builder.RegisterGeneric(typeof(EntityFrameworkRepository <>)) .As(typeof(IRepository <>)) .InstancePerLifetimeScope(); //work context builder.RegisterType <WebWorkContext>().As <IWorkContext>().InstancePerLifetimeScope(); // Services builder.RegisterType <EmployeeService>().As <IEmployeeService>().InstancePerLifetimeScope(); builder.RegisterType <ConsumptionService>().As <IConsumptionService>().InstancePerLifetimeScope(); builder.RegisterType <EmployeeTimesheetService>() .As <ITimesheetService <WorkTimeStatistic> >() .InstancePerLifetimeScope(); builder.RegisterType <ConsumptionTimesheetService>() .As <ITimesheetService <ConsumptionStatistic> >() .InstancePerLifetimeScope(); builder.RegisterType <CustomerService>().As <ICustomerService>().InstancePerLifetimeScope(); builder.RegisterType <StoreSaleService>().As <IStoreSaleService>().InstancePerLifetimeScope(); builder.RegisterType <PostRetailService>().As <IPostRetailService>().InstancePerLifetimeScope(); builder.RegisterType <CategoryService>().As <ICategoryService>().InstancePerLifetimeScope(); builder.RegisterType <InventoryService>().As <IInventoryService>().InstancePerLifetimeScope(); builder.RegisterType <PaymentService>().As <IPaymentService>().InstancePerLifetimeScope(); builder.RegisterType <ProductService>().As <IProductService>().InstancePerLifetimeScope(); builder.RegisterType <OrderService>().As <IOrderService>().InstancePerLifetimeScope(); builder.RegisterType <UserService>().As <IUserService>().InstancePerLifetimeScope(); builder.RegisterType <EncryptionService>().As <IEncryptionService>().InstancePerLifetimeScope(); builder.RegisterType <StandardPermissionProvider>().As <IPermissionProvider>().InstancePerLifetimeScope(); builder.RegisterType <ProductPriceService>().As <IProductPriceService>().InstancePerLifetimeScope(); builder.RegisterType <PermissionService>().As <IPermissionService>().InstancePerLifetimeScope(); builder.RegisterType <AclService>().As <IAclService>().InstancePerLifetimeScope(); builder.RegisterType <StoreService>().As <IStoreService>().InstancePerLifetimeScope(); builder.RegisterType <ExportManager>().As <IExportManager>().InstancePerLifetimeScope(); builder.RegisterType <FormsAuthenticationService>().As <IAuthenticationService>().InstancePerLifetimeScope(); builder.RegisterType <DateTimeHelper>().As <IDateTimeHelper>().InstancePerLifetimeScope(); builder.RegisterType <PageHeadBuilder>().As <IPageHeadBuilder>().InstancePerLifetimeScope(); builder.RegisterType <RoutePublisher>().As <IRoutePublisher>().SingleInstance(); }
public UserInfoDAL() { db = new EntityFrameworkDbContext(); }
public ProductViewingInfosRepository(EntityFrameworkDbContext entityFrameworkDbContext) : base(entityFrameworkDbContext) { }
public HomeController(EntityFrameworkDbContext dbContext) { _dbContext = dbContext; }
public ContentContentTypesRepository(EntityFrameworkDbContext entityFrameworkDbContext) : base(entityFrameworkDbContext) { }