public static TEntity Attach <TEntity>(this System.Data.Entity.DbContext dbContext, TEntity entity, bool isNew) where TEntity : class { if (isNew) { entity = dbContext.Set <TEntity>().Add(entity); dbContext.Entry(entity).State = EntityState.Added; } else { entity = dbContext.Set <TEntity>().Attach(entity); dbContext.Entry(entity).State = EntityState.Modified; } return(entity); }
/// <summary> /// The save or update. /// </summary> /// <param name="entity"> /// The entity. /// </param> /// <returns> /// The <see cref="T"/>. /// </returns> public virtual T SaveOrUpdate(T entity) { if (entity == null) { return(null); } if (entity.IsTransient()) { _dbContext.Set <T>().Add(entity); } //// _dbContext.SaveChanges(); return(entity); }
public void Init(System.Data.Entity.DbContext db) { List <Tuple <string, string> > l = new List <Tuple <string, string> >(); l.Add(Tuple.Create("管理主页", "supervise/main/index")); l.Add(Tuple.Create("审核", "supervise/audit/index")); l.Add(Tuple.Create("用户", "supervise/appusers/index")); l.Add(Tuple.Create("货币", "supervise/coin/index")); l.Add(Tuple.Create("合约", "supervise/contracts/index")); l.Add(Tuple.Create("论坛", "supervise/forum/index")); l.Add(Tuple.Create("帮助", "supervise/helper/index")); l.Add(Tuple.Create("新闻", "supervise/new/index")); l.Add(Tuple.Create("数据", "supervise/tradedata/index")); l.Add(Tuple.Create("安全", "supervise/security/index")); l.Add(Tuple.Create("监控", "supervise/snap/index")); l.Add(Tuple.Create("参数", "supervise/parameter/index")); l.Add(Tuple.Create("网站参数", "supervise/siteParameter/index")); l.Add(Tuple.Create("交易用户", "supervise/appusers/index")); List <Menu> lm = new List <Menu>(); for (int i = 0; i < l.Count; i++) { var m = new Menu { Id = i + 1, Name = l[i].Item1, Url = l[i].Item2 }; lm.Add(m); } db.Set <Menu>().AddOrUpdate(lm.ToArray()); db.SaveChanges(); }
static public System.Collections.Generic.List <T> queryData <T>(object db, object where) where T : class { Expression <Func <T, bool> > Where = where as Expression <Func <T, bool> >; System.Data.Entity.DbContext Db = db as System.Data.Entity.DbContext; return(Db.Set <T>().Where(Where).ToList()); }
/// <summary> /// 定义种子数据初始化过程 /// </summary> /// <param name="context">数据上下文</param> public void Action(System.Data.Entity.DbContext context) { context.Set <SysRole>() .Add(new SysRole() { Name = "超级管理员", Remark = "超级管理员角色,拥有系统最高权限", IsAdmin = true, IsSystem = true, IsLocked = false, CreatedTime = DateTime.Now }); }
public RepositoryCacheService(DbContext context) { _contextCache = new ConcurrentDictionary <Type, ConcurrentDictionary <int, BaseEntity> >(); var entityTypes = Utils.GetTypeByParent(typeof(BaseEntity)); entityTypes.ForEach(entityType => { var entites = context.Set(entityType) .IncludeAll(entityType) .ToListAsync() .Result .Select(e => new KeyValuePair <int, BaseEntity>(((BaseEntity)e).Id, (BaseEntity)e)); _contextCache.TryAdd(entityType, new ConcurrentDictionary <int, BaseEntity>(entites)); }); }
public int Add <T>(T t) where T : class { PropertyInfo createDate = typeof(T).GetProperty("CreateDate"); PropertyInfo updateDate = typeof(T).GetProperty("UpdateDate"); PropertyInfo isDeleted = typeof(T).GetProperty("IsDeleted"); //默认数据 if (createDate != null) { createDate.SetValue(t, DateTime.Now); } if (updateDate != null) { updateDate.SetValue(t, DateTime.Now); } if (isDeleted != null) { isDeleted.SetValue(t, false);//添加时默认设置为未删除 } _dbContext.Set <T>().Add(t); return(SaveChanges()); }
/// <summary> /// 所有文件(夹)列表 /// </summary> /// <param name="folderId">文件夹Id</param> /// <param name="userId">用户Id</param> /// <returns></returns> public IEnumerable <FileInfoEntity> GetList(string folderId, string userId) { var folder = "folder"; var query1 = from q in _context.Set <FileFolderEntity>() where q.DeleteMark == 0 select new { FileId = q.FolderId, FolderId = q.ParentId, FileName = q.FolderName, FileSize = string.Empty, FileType = folder, q.CreateUserId, q.ModifyDate, q.IsShare, FilePath = string.Empty }; var query2 = from q in _context.Set <FileInfoEntity>() where q.DeleteMark == 0 select new { q.FileId, q.FolderId, q.FileName, q.FileSize, q.FileType, q.CreateUserId, q.ModifyDate, q.IsShare, q.FilePath }; var query = query2.Concat(query1); if (!string.IsNullOrEmpty(folderId)) { query = query.Where(x => x.FolderId == folderId); } else { query = query.Where(x => x.FolderId == "0"); } var data = query.OrderBy(x => x.ModifyDate).ToList(); return(data.Select(x => new FileInfoEntity { FileId = x.FileId, FolderId = x.FolderId, FileName = x.FileName, FileSize = x.FileSize, FileType = x.FileType, CreateUserId = x.CreateUserId, ModifyDate = x.ModifyDate, IsShare = x.IsShare, FilePath = x.FilePath }).ToList()); //var strSql = new StringBuilder(); //strSql.Append(@"SELECT * // FROM ( SELECT FolderId AS FileId , // ParentId AS FolderId , // FolderName AS FileName , // '' AS FileSize , // 'folder' AS FileType , // CreateUserId, // ModifyDate, // IsShare, // '' as FilePath // FROM Base_FileFolder where DeleteMark = 0 // UNION // SELECT FileId , // FolderId , // FileName , // FileSize , // FileType , // CreateUserId, // ModifyDate, // IsShare, // FilePath // FROM Base_FileInfo where DeleteMark = 0 // ) t WHERE "); //var parameter = new List<DbParameter>(); //strSql.Append(" CreateUserId = @userId"); //parameter.Add(DbParameters.CreateDbParameter("@userId", userId)); //if (!folderId.IsEmpty()) //{ // strSql.Append(" AND FolderId = @folderId"); // parameter.Add(DbParameters.CreateDbParameter("@folderId", folderId)); //} //else //{ // strSql.Append(" AND FolderId = '0'"); //} //strSql.Append(" ORDER BY ModifyDate ASC"); //return this.BaseRepository().FindList(strSql.ToString(), parameter.ToArray()); }
public FileInfoService() { _context = (DbFactory.Base() as Data.EF.Database).dbcontext; fileInfoEntities = _context.Set <FileInfoEntity>(); }
public ICollection <T> GetAll() { IQueryable <T> query = ctx.Set <T>(); return(query.ToList <T>()); }
public IQueryable <TEntity> Get() { IQueryable <TEntity> query = _context.Set <TEntity>(); return(query); }
public IQueryable <T> AsQueryable() { return(_context.Set <T>().AsQueryable()); }
public FilterableDbSet(System.Data.Entity.DbContext context, Expression <Func <TEntity, bool> > filter) : this(context.Set <TEntity>(), filter) { }
public Repository() { db = new SchoolDBContext(); dbSet = db.Set <T>(); }
public IDbSet <T> GetDbSet() { return(_context.Set <T>()); }
public DbSet <TEntity> DbSet <TEntity>() where TEntity : class { return(_context.Set <TEntity>()); }
public Tentity SingleOrDefault(Expression <Func <Tentity, bool> > predicate) { return(context.Set <Tentity>().SingleOrDefault(predicate)); }
/// <summary> /// Gets the queryable. /// </summary> /// <param name="entityType">Type of the entity.</param> /// <param name="entityFields">The entity fields.</param> /// <param name="attributes">The attributes.</param> /// <param name="selectComponents">The select components.</param> /// <param name="sortProperty">The sort property.</param> /// <param name="dataViewFilterOverrides">The data view filter overrides.</param> /// <param name="databaseTimeoutSeconds">The database timeout seconds.</param> /// <param name="isCommunication">if set to <c>true</c> [is communication].</param> /// <param name="errorMessages">The error messages.</param> /// <param name="reportDbContext">The report database context.</param> /// <returns></returns> /// <exception cref="Exception"></exception> public IQueryable GetQueryable(Type entityType, Dictionary <int, EntityField> entityFields, Dictionary <int, AttributeCache> attributes, Dictionary <int, ReportField> selectComponents, Rock.Web.UI.Controls.SortProperty sortProperty, DataViewFilterOverrides dataViewFilterOverrides, int?databaseTimeoutSeconds, bool isCommunication, out List <string> errorMessages, out System.Data.Entity.DbContext reportDbContext) { errorMessages = new List <string>(); reportDbContext = null; if (entityType != null) { reportDbContext = Reflection.GetDbContextForEntityType(entityType); IService serviceInstance = Reflection.GetServiceForEntityType(entityType, reportDbContext); if (databaseTimeoutSeconds.HasValue) { reportDbContext.Database.CommandTimeout = databaseTimeoutSeconds.Value; } if (serviceInstance != null) { ParameterExpression paramExpression = serviceInstance.ParameterExpression; MemberExpression idExpression = Expression.Property(paramExpression, "Id"); // Get AttributeValue queryable and parameter var attributeValues = reportDbContext.Set <AttributeValue>(); ParameterExpression attributeValueParameter = Expression.Parameter(typeof(AttributeValue), "v"); // Create the dynamic type var dynamicFields = new Dictionary <string, Type>(); dynamicFields.Add("Id", typeof(int)); foreach (var f in entityFields) { dynamicFields.Add(string.Format("Entity_{0}_{1}", f.Value.Name, f.Key), f.Value.PropertyType); } foreach (var a in attributes) { dynamicFields.Add(string.Format("Attribute_{0}_{1}", a.Value.Id, a.Key), a.Value.FieldType.Field.AttributeValueFieldType); } foreach (var reportField in selectComponents) { DataSelectComponent selectComponent = DataSelectContainer.GetComponent(reportField.Value.DataSelectComponentEntityType.Name); if (selectComponent != null) { dynamicFields.Add(string.Format("Data_{0}_{1}", selectComponent.ColumnPropertyName, reportField.Key), selectComponent.ColumnFieldType); var customSortProperties = selectComponent.SortProperties(reportField.Value.Selection); if (customSortProperties != null) { foreach (var customSortProperty in customSortProperties.Split(',')) { if (!string.IsNullOrWhiteSpace(customSortProperty)) { var customSortPropertyType = entityType.GetPropertyType(customSortProperty); dynamicFields.Add(string.Format("Sort_{0}_{1}", customSortProperty, reportField.Key), customSortPropertyType ?? typeof(string)); } } } if (isCommunication && selectComponent is IRecipientDataSelect) { dynamicFields.Add($"Recipient_{selectComponent.ColumnPropertyName}_{reportField.Key}", ((IRecipientDataSelect)selectComponent).RecipientColumnFieldType); } } } if (dynamicFields.Count == 0) { errorMessages.Add("At least one field must be defined"); return(null); } Type dynamicType = LinqRuntimeTypeBuilder.GetDynamicType(dynamicFields); ConstructorInfo methodFromHandle = dynamicType.GetConstructor(Type.EmptyTypes); // Bind the dynamic fields to their expressions var bindings = new List <MemberAssignment>(); bindings.Add(Expression.Bind(dynamicType.GetField("id"), idExpression)); foreach (var f in entityFields) { bindings.Add(Expression.Bind(dynamicType.GetField(string.Format("entity_{0}_{1}", f.Value.Name, f.Key)), Expression.Property(paramExpression, f.Value.Name))); } foreach (var a in attributes) { bindings.Add(Expression.Bind(dynamicType.GetField(string.Format("attribute_{0}_{1}", a.Value.Id, a.Key)), GetAttributeValueExpression(attributeValues, attributeValueParameter, idExpression, a.Value.Id))); } foreach (var reportField in selectComponents) { DataSelectComponent selectComponent = DataSelectContainer.GetComponent(reportField.Value.DataSelectComponentEntityType.Name); if (selectComponent != null) { try { var componentExpression = selectComponent.GetExpression(reportDbContext, idExpression, reportField.Value.Selection ?? string.Empty); if (componentExpression == null) { componentExpression = Expression.Constant(null, typeof(string)); } bindings.Add(Expression.Bind(dynamicType.GetField(string.Format("data_{0}_{1}", selectComponent.ColumnPropertyName, reportField.Key)), componentExpression)); if (isCommunication && selectComponent is IRecipientDataSelect) { var recipientPersonIdExpression = ((IRecipientDataSelect)selectComponent).GetRecipientPersonIdExpression(reportDbContext, idExpression, reportField.Value.Selection ?? string.Empty); if (recipientPersonIdExpression != null) { bindings.Add(Expression.Bind(dynamicType.GetField(string.Format("recipient_{0}_{1}", selectComponent.ColumnPropertyName, reportField.Key)), recipientPersonIdExpression)); } } var customSortProperties = selectComponent.SortProperties(reportField.Value.Selection); if (!string.IsNullOrEmpty(customSortProperties)) { foreach (var customSortProperty in customSortProperties.Split(',')) { var customSortPropertyParts = customSortProperty.Split('.'); MemberInfo memberInfo = dynamicType.GetField(string.Format("sort_{0}_{1}", customSortProperty, reportField.Key)); Expression memberExpression = null; foreach (var customSortPropertyPart in customSortPropertyParts) { memberExpression = Expression.Property(memberExpression ?? paramExpression, customSortPropertyPart); } bindings.Add(Expression.Bind(memberInfo, memberExpression)); } } } catch (Exception ex) { throw new Exception(string.Format("Exception in {0}", selectComponent), ex); } } } ConstructorInfo constructorInfo = dynamicType.GetConstructor(Type.EmptyTypes); NewExpression newExpression = Expression.New(constructorInfo); MemberInitExpression memberInitExpression = Expression.MemberInit(newExpression, bindings); LambdaExpression selector = Expression.Lambda(memberInitExpression, paramExpression); // NOTE: having a NULL Dataview is OK. Expression whereExpression = null; if (this.DataView != null) { whereExpression = this.DataView.GetExpression(serviceInstance, paramExpression, dataViewFilterOverrides, out errorMessages); } MethodInfo getMethod = serviceInstance.GetType().GetMethod("Get", new Type[] { typeof(ParameterExpression), typeof(Expression), typeof(Rock.Web.UI.Controls.SortProperty), typeof(int?) }); if (getMethod != null) { var getResult = getMethod.Invoke(serviceInstance, new object[] { paramExpression, whereExpression, null, null }); var qry = getResult as IQueryable <IEntity>; var qryExpression = qry.Expression; // apply the OrderBy clauses to the Expression from whatever columns are specified in sortProperty.Property string orderByMethod = "OrderBy"; if (sortProperty == null) { // if no sorting was specified, sort by Id sortProperty = new Web.UI.Controls.SortProperty { Direction = SortDirection.Ascending, Property = "Id" }; } /* * NOTE: The sort property sorting rules can be a little confusing. Here is how it works: * - SortProperty.Direction of Ascending means sort exactly as what the Columns specification says * - SortProperty.Direction of Descending means sort the _opposite_ of what the Columns specification says * Examples: * 1) SortProperty.Property "LastName desc, FirstName, BirthDate desc" and SortProperty.Direction = Ascending * OrderBy should be: "order by LastName desc, FirstName, BirthDate desc" * 2) SortProperty.Property "LastName desc, FirstName, BirthDate desc" and SortProperty.Direction = Descending * OrderBy should be: "order by LastName, FirstName desc, BirthDate" */ foreach (var column in sortProperty.Property.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { string propertyName; var direction = sortProperty.Direction; if (column.EndsWith(" desc", StringComparison.OrdinalIgnoreCase)) { propertyName = column.Left(column.Length - 5); // if the column ends with " desc", toggle the direction if sortProperty is Descending direction = sortProperty.Direction == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending; } else { propertyName = column; } string methodName = direction == SortDirection.Descending ? orderByMethod + "Descending" : orderByMethod; // Call OrderBy on whatever the Expression is for that Column var sortMember = bindings.FirstOrDefault(a => a.Member.Name.Equals(propertyName, StringComparison.OrdinalIgnoreCase)); LambdaExpression sortSelector = Expression.Lambda(sortMember.Expression, paramExpression); qryExpression = Expression.Call(typeof(Queryable), methodName, new Type[] { qry.ElementType, sortSelector.ReturnType }, qryExpression, sortSelector); orderByMethod = "ThenBy"; } var selectExpression = Expression.Call(typeof(Queryable), "Select", new Type[] { qry.ElementType, dynamicType }, qryExpression, selector); var query = qry.Provider.CreateQuery(selectExpression).AsNoTracking(); // cast to a dynamic so that we can do a Queryable.Take (the compiler figures out the T in IQueryable at runtime) dynamic dquery = query; if (FetchTop.HasValue) { dquery = Queryable.Take(dquery, FetchTop.Value); } return(dquery as IQueryable); } } } return(null); }
public TEntity Get(int id) { return(Context.Set <TEntity>().Find(id)); }
public Repository(DbContext context) { this.context = context; this.dbSet = context.Set <TEntity>(); }
public EduAnswerService() { _context = (DbFactory.Base() as Data.EF.Database).dbcontext; eduAnswerEntities = _context.Set <EduAnswerEntity>(); }
public Repository() { db = new LibrarySystemContext(); dbSet = db.Set <T>(); }
public Repository() { db = new EventManagerSystemContext(); dbSet = db.Set <T>(); }