public DbContext CreateDbContex <TDbContext>(string connectionString, IIocResolve iocResolve) where TDbContext : DbContext { DbContext dbContext; ActiveTransactionInfo activeTransaction; activeTransaction = ActiveTransations.TryGetValue(connectionString, out activeTransaction) ? activeTransaction : default(ActiveTransactionInfo); if (activeTransaction == null)//没找到则ioc通过NamedParameter创建一个 { dbContext = iocResolve.ResolveParameter <TDbContext>(new NamedParameter("nameOrConnectionString", connectionString)); var dbTransaction = dbContext.Database.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted); activeTransaction = new ActiveTransactionInfo(dbTransaction, dbContext); ActiveTransations[connectionString] = activeTransaction; } else//找到了则通过ioc把DbConnection作为参数创建一个DbContext { dbContext = iocResolve.ResolveParameter <TDbContext>(new Parameter[] { new NamedParameter("existingConnection", activeTransaction.DbContextTransaction.UnderlyingTransaction.Connection), new NamedParameter("contextOwnsConnection", false) }); //通过connection参数resolve一个dbcontext对象 //dbContext = iocResolve.ResolveParameter<TDbContext>(new TypedParameter(typeof(DbConnection), //activeTransaction.DbContextTransaction.UnderlyingTransaction.Connection)); dbContext.Database.UseTransaction(activeTransaction.DbContextTransaction.UnderlyingTransaction); activeTransaction.AttendedDbContexts.Add(dbContext); } DbContexts.Add(dbContext); return(dbContext); }
public RemoveBooksDialog(params Account[] accounts) { _libraryBooks = DbContexts.GetLibrary_Flat_NoTracking(); _accounts = accounts; InitializeComponent(); this.Load += (_, _) => this.RestoreSizeAndLocation(Configuration.Instance); this.FormClosing += (_, _) => this.SaveSizeAndLocation(Configuration.Instance); _labelFormat = label1.Text; _dataGridView.CellContentClick += (_, _) => _dataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit); _dataGridView.CellValueChanged += (_, _) => UpdateSelection(); _dataGridView.BindingContextChanged += _dataGridView_BindingContextChanged; var orderedGridEntries = _libraryBooks .Select(lb => new RemovableGridEntry(lb)) .OrderByDescending(ge => (DateTime)ge.GetMemberValue(nameof(ge.PurchaseDate))) .ToList(); _removableGridEntries = new SortableBindingList <RemovableGridEntry>(orderedGridEntries); gridEntryBindingSource.DataSource = _removableGridEntries; _dataGridView.Enabled = false; }
/// <summary> /// Dispose /// </summary> /// <param name="iocResolve"></param> public virtual void Dispose(IIocResolve iocResolve) { foreach (var activeTransaction in ActiveTransations.Values) { foreach (var attendedDbContext in activeTransaction.AttendedDbContexts) { iocResolve.Release(attendedDbContext); } activeTransaction.DbContextTransaction.Dispose(); iocResolve.Release(activeTransaction.StartDbContext); } //清除事务 ActiveTransations.Clear(); foreach (var dbContext in DbContexts) { iocResolve.Release(dbContext); } //清除DbContexts DbContexts.Clear(); if (CurrentTransaction == null) { return; } CurrentTransaction.Dispose(); CurrentTransaction = null; }
public void Dispose() { if (_disposed) { return; } if (!_nested) { if (!_completed) { SaveChanges(); } DbContexts.Dispose(); } RemoveAmbientScope(); if (_parentScope != null) { if (!_parentScope._disposed) { SetAmbientScope(_parentScope); } } _disposed = true; }
/// <summary> /// 保存数据 /// </summary> public void SaveImportData(IEnumerable <Spl_Person> personList) { try { DbContexts db = new DbContexts(); foreach (var model in personList) { Spl_Person entity = new Spl_Person(); entity.KEY_Id = ResultHelper.NewId; entity.Name = model.Name; entity.Sex = model.Sex; entity.Age = model.Age; entity.IDCard = model.IDCard; entity.Phone = model.Phone; entity.Email = model.Email; entity.Address = model.Address; entity.CreateTime = ResultHelper.NowTime.ToString("yyyy-MM-dd HH:mm:ss"); entity.Region = model.Region; entity.Category = model.Category; db.Spl_Person.Add(entity); } db.SaveChanges(); } catch (Exception ex) { throw; } }
public virtual DbContext CreateDbContext <TDbContext>(string connectionString, IDbContextResolver dbContextResolver) where TDbContext : DbContext { var dbContext = dbContextResolver.Resolve <TDbContext>(connectionString); DbContexts.Add(dbContext); return(dbContext); }
//保存头像 public int bao(DTO.UserInfoDto du) { var ui = DbContexts.UserInfo.Find(du.Id); ui.UserHeadPortrait = du.UserHeadPortrait; return(DbContexts.SaveChanges()); }
/// <summary> /// 我的微博删除微博 /// </summary> /// <param name="id"></param> /// <returns></returns> public int Remove(int id) { var RemoveMymicrobolg = DbContexts.MicroBlog.Find(id); DbContexts.MicroBlog.Remove(RemoveMymicrobolg); return(DbContexts.SaveChanges()); }
public IGenericEFRepository <TEntity> Repository <TContext, TEntity>() where TContext : DbContext where TEntity : class { return((IGenericEFRepository <TEntity>)_repositories.GetOrAdd( typeof(TEntity), t => _repositoryFactory.Get <TEntity>(DbContexts.Get <TContext>()) )); }
public static LibraryBook GetSingleLibraryBook(string productId) { using var context = DbContexts.GetContext(); var libraryBook = context .Library .GetLibrary() .SingleOrDefault(lb => lb.Book.AudibleProductId == productId); return(libraryBook); }
private void setBackupCounts(object _, object __) { var books = DbContexts.GetContext() .GetLibrary_Flat_NoTracking() .Select(sp => sp.Book) .ToList(); setBookBackupCounts(books); setPdfBackupCounts(books); }
public ClientService(UserManager <CustomIdentityUser> usermanager, IEMailService mailService, ICartRepo CartService, IConfiguration configurations, IHttpContextAccessor httpContextAccessor, IMapper mapper, DbContexts dbContexts) { _UserManager = usermanager; _CartRepo = CartService; _Configurations = configurations; _mailService = mailService; _mapper = mapper; _DbContext = dbContexts; }
/// <summary> /// 找回密码方法 /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> public int ForgetThePwd(DTO.UserInfoDto Uidto) { //根据邮箱修改密码 var ForgetThePwdEntity = DbContexts.UserInfo.Where(p => p.UserEmail == Uidto.UserEmail).First(); ForgetThePwdEntity.UserPassword = Uidto.UserPassword; int i = DbContexts.SaveChanges(); return(i); }
protected static async Task RunAsync(Processable Processable) { foreach (var libraryBook in Processable.GetValidLibraryBooks(DbContexts.GetLibrary_Flat_NoTracking())) { await ProcessOneAsync(Processable, libraryBook, false); } var done = "Done. All books have been processed"; Console.WriteLine(done); Serilog.Log.Logger.Information(done); }
//保存资料 public int update(DTO.UserInfoDto du) { var ui = DbContexts.UserInfo.Find(du.Id); ui.UserName = du.UserName; ui.UserEmail = du.UserEmail; ui.UserAutograph = du.UserAutograph; ui.UserSex = du.UserSex; ui.UserRegion = du.UserRegion; ui.UserBirthday = du.UserBirthday; return(DbContexts.SaveChanges()); }
public List <UserView> GetRoleListByUser(string roleId, string depId) { String sql = "select a.Id,a.UserName,a.TrueName,ISNULL(b.SysUserId, '0') as Flag from SysUser a left join SysRoleSysUser b on cast(a.Id as varchar) = b.SysUserId and b.SysRoleId = @SysRoleId Where a.DepId = @DepId order by b.SysUserId desc"; SqlParameter[] sqlParameters = { new SqlParameter { ParameterName = "SysRoleId", Value = roleId }, new SqlParameter{ ParameterName = "DepId", Value = depId } }; DbContexts DbContext = new DbContexts(); return(DbContext.Database.SqlQuery <UserView>(sql, sqlParameters).ToList()); }
/// <summary> /// 注册方法 /// </summary> /// <param name="whereLambda"></param> /// <returns></returns> public int AddRegister(DTO.UserInfoDto Uidto) { //return DbContext.UserInfo.Where(whereLambda).AsQueryable(); Models.UserInfo Userlist = new Models.UserInfo() { UserName = Uidto.UserName, UserEmail = Uidto.UserEmail, UserPassword = Uidto.UserPassword }; DbContexts.UserInfo.Add(Userlist); int i = DbContexts.SaveChanges(); return(i); }
private static LibraryBook getNextValidBook(this IProcessable processable) { var libraryBooks = DbContexts.GetContext().GetLibrary_Flat_NoTracking(); foreach (var libraryBook in libraryBooks) { if (processable.Validate(libraryBook)) { return(libraryBook); } } return(null); }
public override void Commit() { DbContexts.ForEach(dtx => { var CurrentTransaction = dataBaseTransactions.FirstOrDefault(t => t.dbContext == dtx); if (CurrentTransaction != null) { CurrentTransaction.Transaction.Commit(); CurrentTransaction.isCommit = true; CurrentTransaction.Transaction.Dispose(); } } ); }
/// <summary> /// 发布微博 /// </summary> /// <param name="Uid"></param> /// <param name="Mbd"></param> /// <returns></returns> public int PublishWeibo(DTO.UserInfoDto Uid, DTO.MicroBlogsDto Mbd) { Models.MicroBlog Mb = new Models.MicroBlog() { UserID = Uid.Id, Title = Mbd.Title, Content_text = Mbd.Content_text, Content_img = Mbd.Content_img, Points_number = 0, Place = Mbd.Place, Cansee_states = 0 }; DbContexts.MicroBlog.Add(Mb); return(DbContexts.SaveChanges()); }
public virtual void Dispose(IIocResolver iocResolver) { foreach (var dbContext in DbContexts) { iocResolver.Release(dbContext); } DbContexts.Clear(); if (CurrentTransaction != null) { CurrentTransaction.Dispose(); CurrentTransaction = null; } }
public void Display() { if (hasBeenDisplayed) { return; } hasBeenDisplayed = true; // // transform into sorted GridEntry.s BEFORE binding // context = DbContexts.GetContext(); var lib = context.GetLibrary_Flat_WithTracking(); // if no data. hide all columns. return if (!lib.Any()) { for (var i = dataGridView.ColumnCount - 1; i >= 0; i--) { dataGridView.Columns.RemoveAt(i); } return; } var orderedGridEntries = lib .Select(lb => new GridEntry(lb)).ToList() // default load order .OrderByDescending(ge => ge.Purchase_Date) //// more advanced example: sort by author, then series, then title //.OrderBy(ge => ge.Authors) // .ThenBy(ge => ge.Series) // .ThenBy(ge => ge.Title) .ToList(); // // BIND // gridEntryBindingSource.DataSource = orderedGridEntries.ToSortableBindingList(); // // FILTER // filter(); BackupCountsChanged?.Invoke(this, EventArgs.Empty); }
/// <summary> /// 加入异常日志 /// </summary> /// <param name="ex">异常</param> public static void WriteException(Exception ex) { SysConfigModel siteConfig = new SysConfigBLL().loadConfig(Utils.GetXmlMapPath("Configpath")); //后台异常开启 if (siteConfig.exceptionstatus == 1) { try { using (DbContexts db = new DbContexts()) { SysException model = new SysException() { ExceptionId = ResultHelper.NewId, HelpLink = ex.HelpLink, Message = ex.Message, Source = ex.Source, StackTrace = ex.StackTrace, TargetSite = ex.TargetSite.ToString(), Data = ex.Data.ToString(), CreateTime = ResultHelper.NowTime.ToString() }; db.SysException.Add(model); db.SaveChanges(); } } catch (Exception ep) { string subFold = DateTime.Now.Year + DateTime.Now.Month.ToString("D2"); string fileName = subFold + DateTime.Now.Day.ToString("D2") + ".txt"; string path = System.Web.HttpContext.Current.Server.MapPath("~/LogFile/") + subFold; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string wholePath = path + "\\" + fileName; using (StreamWriter sw = new StreamWriter(wholePath, true, Encoding.UTF8)) { sw.WriteLine((ex.Message + "|" + ex.StackTrace + "|" + ep.Message + "|" + DateTime.Now.ToString()).ToString()); sw.Dispose(); sw.Close(); } return; } } }
/// <summary> /// 删除发送者的全部消息(非物理删除) /// </summary> /// <param name="sender"></param> public void DeleteMessageAllNotBySender(string sender) { using (DbContexts db = new DbContexts()) { IQueryable <MIS_WebIM_Message> entityList = from r in db.MIS_WebIM_Message where r.Sender == sender select r; if (entityList == null) { return; } foreach (var entity in entityList) { entity.State = "true"; } db.SaveChanges(); } }
public void Display() { if (hasBeenDisplayed) { return; } hasBeenDisplayed = true; // // transform into sorted GridEntry.s BEFORE binding // var lib = DbContexts.GetLibrary_Flat_NoTracking(); // if no data. hide all columns. return if (!lib.Any()) { for (var i = _dataGridView.ColumnCount - 1; i >= 0; i--) { _dataGridView.Columns.RemoveAt(i); } return; } var orderedGridEntries = lib .Select(lb => { var entry = new GridEntry(lb); entry.Committed += (_, __) => Filter(); return(entry); }).ToList() // default load order .OrderByDescending(ge => (DateTime)ge.GetMemberValue(nameof(ge.PurchaseDate))) //// more advanced example: sort by author, then series, then title //.OrderBy(ge => ge.Authors) // .ThenBy(ge => ge.Series) // .ThenBy(ge => ge.Title) .ToList(); // BIND gridEntryBindingSource.DataSource = new SortableBindingList <GridEntry>(orderedGridEntries); // FILTER Filter(); }
/// <summary> /// 增加点赞数 /// </summary> /// <param name="id"></param> /// <param name="Points"></param> public int Points_number(int id) { var PreviewBlogEntity = (from mb in DbContexts.MicroBlog where mb.Id == id select new { mb.Points_number }); int num = 0; foreach (var item in PreviewBlogEntity) { num = item.Points_number; } num += 1; var dd = DbContexts.MicroBlog.Find(id); dd.Points_number = num; return(DbContexts.SaveChanges()); //Models.MicroBlog mbs = new Models.MicroBlog() { // Points_number=num //}; }
/// <summary> /// 返回接收者一个消息 /// </summary> /// <param name="receiver"></param> /// <param name="id"></param> /// <returns></returns> public MIS_WebIM_MessageRecModel GetMessageByReceiver(string receiver, string id) { using (DbContexts db = new DbContexts()) { var model = (from m in db.MIS_WebIM_Message join r in db.MIS_WebIM_Message_Rec on m.Id.ToString() equals r.MessageId where m.Id.ToString() == id where r.receiver == receiver select new MIS_WebIM_MessageRecModel { Id = m.Id, Message = m.Message, Sender = m.Sender, receiver = r.receiver, State = r.State, SendDt = m.SendDt, RecDt = r.RecDt }).SingleOrDefault(); return(model); } }
public static string GetJobExecuteTime(string id) { using (DbContexts db = new DbContexts()) { ////定义trigger名称 //string triggerName="Trigger_"+id; //ObjectResult<P_QRTZ_GetJobExecuteTime_Result> result = db.P_QRTZ_GetJobExecuteTime(triggerName); //if (result == null) //{ // return ""; //} //var tigResult = result.SingleOrDefault(); //if (tigResult == null) //{ // return ""; //} long starttime = tigResult.START_TIME; TimeSpan t = new TimeSpan(0); DateTimeOffset df = new DateTimeOffset(starttime, t); return(df.DateTime.ToLocalTime().ToString()); } }
/// <summary>Process the first valid product. Create default context</summary> /// <returns>Returns either the status handler from the process, or null if all books have been processed</returns> public static async Task <StatusHandler> ProcessSingleAsync(this IProcessable processable, string productId) { using var context = DbContexts.GetContext(); var libraryBook = context .Library .GetLibrary() .SingleOrDefault(lb => lb.Book.AudibleProductId == productId); if (libraryBook == null) { return(null); } if (!processable.Validate(libraryBook)) { return new StatusHandler { "Validation failed" } } ; return(await processBookAsync(processable, libraryBook)); }
public List <UserView> GetMatchingListByUser(string matchingId, string depId, string name) { if (string.IsNullOrEmpty(name)) { name = string.Empty; } if (string.IsNullOrEmpty(depId)) { depId = string.Empty; } //String sql = "select a.Id,a.UserName,a.TrueName,ISNULL(b.OTM, '0') as Flag from SysUser a left join FIX_MatchingModel b on cast(a.Id as varchar) = b.OTM and b.Id = @matchingId Where a.DepId = @DepId and a.TrueName = '@name' order by b.OTM desc"; String sql = "select a.Id,a.UserName,a.TrueName,ISNULL(b.OTM, '0') as Flag from SysUser a left join FIX_MatchingModel b on cast(a.Id as varchar) = b.OTM and b.Id = @matchingId Where a.DepId = @DepId order by b.OTM desc"; //SqlParameter[] sqlParameters = { new SqlParameter { ParameterName = "matchingId", Value = matchingId }, new SqlParameter { ParameterName = "DepId", Value = depId }, new SqlParameter { ParameterName = "name", Value = name } }; SqlParameter[] sqlParameters = { new SqlParameter { ParameterName = "matchingId", Value = matchingId }, new SqlParameter{ ParameterName = "DepId", Value = depId } }; DbContexts DbContext = new DbContexts(); return(DbContext.Database.SqlQuery <UserView>(sql, sqlParameters).ToList()); }