public bool Apply(EF.Shop_Photo photo, EF.Shop_People people, EF.Shop_Store shop) { //TransactionScope有错误自己回滚 using (TransactionScope tran = new TransactionScope()) { try { DbEntityEntry<EF.Shop_Photo> entry = db.Entry<EF.Shop_Photo>(photo); entry.State = EntityState.Added; db.SaveChanges(); shop.PhotoId = photo.PhotoId; people.BoolLX = true; DbEntityEntry<EF.Shop_People> entry1 = db.Entry<EF.Shop_People>(people); entry1.State = EntityState.Added; db.SaveChanges(); shop.PeopleId = people.PeopleId; shop.BoolPass = false; DbEntityEntry<EF.Shop_Store> entry2 = db.Entry<EF.Shop_Store>(shop); entry2.State = EntityState.Added; db.SaveChanges(); tran.Complete(); return true; } catch (Exception) { tran.Dispose(); return false; throw; } } }
public bool Apply(EF.Shop_Goods goods,EF.Shop_Photo photo) { //TransactionScope有错误自己回滚 using (TransactionScope tran = new TransactionScope()) { try { DbEntityEntry<EF.Shop_Photo> entry0 = db.Entry<EF.Shop_Photo>(photo); entry0.State = EntityState.Added; db.SaveChanges(); goods.PhotoId = photo.PhotoId; goods.BoolYX = true; goods.AddTime = DateTime.Now; DbEntityEntry<EF.Shop_Goods> entry = db.Entry<EF.Shop_Goods>(goods); entry.State = EntityState.Added; db.SaveChanges(); tran.Complete(); return true; } catch (Exception) { tran.Dispose(); return false; throw; } } }
public static PropertyClassDTO MapFieldValues(EF.PropertyClass dbItem) { if (dbItem == null) return null; PropertyClassDTO retVal = new PropertyClassDTO() { ClassNum = dbItem.ClassNum, Name = dbItem.Name }; return retVal; }
public static TownshipDTO MapFieldValues(EF.Township dbItem) { if (dbItem == null) return null; TownshipDTO retVal = new TownshipDTO() { TownNum = dbItem.TownNum, Name = dbItem.Name }; return retVal; }
public static PropertyAddressDTO MapFieldValues(EF.PropertyAddress dbItem) { if (dbItem == null) return null; PropertyAddressDTO dto = new PropertyAddressDTO() { Apt = dbItem.Apt, City = dbItem.City, HouseNum = dbItem.HouseNum, Pin = dbItem.Pin, Street = dbItem.Street, StreetDir = dbItem.StreetDir, Suffix = dbItem.Suffix, Zip = dbItem.Zip }; return dto; }
public static PropertyDTO MapFieldValues(EF.Property dbItem) { if (dbItem == null) return null; var myFact = new PropertyFactory(); PropertyDTO retVal = new PropertyDTO() { Age = dbItem.Age, AirCond = dbItem.AirCond, AptCount = dbItem.AptCount, AtticDesc = dbItem.AtticDesc, BasementDesc = dbItem.BasementDesc, BuildingSF = dbItem.BuildingSF, BuildingUse = dbItem.BuildingUse, ClassNum = dbItem.ClassNum, CommUnits = dbItem.CommUnits, ExtDesc = dbItem.ExtDesc, Fireplace = dbItem.Fireplace, FullBath = dbItem.FullBath, GarageDesc = dbItem.GarageDesc, HalfBath = dbItem.HalfBath, HomeImpYear = dbItem.HomeImpYear, LandSF = dbItem.LandSF, LocationId = dbItem.LocationId, NeighborhoodId = dbItem.NeighborhoodId, Pin = dbItem.Pin, PropertyAddressDTO = PropertyAddressRepository.MapFieldValues(dbItem.PropertyAddress), PropertyClassDTO = PropertyClassRepository.MapFieldValues(dbItem.PropertyClass), PropertyTagDTOs = PropertyTagRepository.MapFieldValues(dbItem.PropertyTags), ResType = dbItem.ResType, SaleAmount = dbItem.SaleAmount, SaleDate = dbItem.SaleDate, TaxCode = dbItem.TaxCode, TotalAllBuildingSF = dbItem.TotalAllBuildingSF, TownNum = dbItem.TownNum, TownshipDTO = TownshipRepository.MapFieldValues(dbItem.Township), UnitsTotal = dbItem.UnitsTotal, Volume = dbItem.Volume }; return retVal; }
public static IEnumerable<EF.FeedItem> GetFeedItems(EF.Feed feed) { XmlReader reader = XmlReader.Create(feed.URL); SyndicationFeed synfeed = SyndicationFeed.Load(reader); reader.Close(); foreach (var single in synfeed.Items.Take(10)) { yield return new EF.FeedItem { Feed = feed, FeedID = feed.FeedID, Title = ((string)single.Title.Text), Link = ((string)single.Links[0].Uri.OriginalString), Summary = ((string)single.Summary.Text), PubDate = Convert.ToDateTime(single.PublishDate.ToString()) }; } }
public int Upload(EF.Shop_Photo photo) { try { DbEntityEntry<EF.Shop_Photo> entry = db.Entry<EF.Shop_Photo>(photo); entry.State = EntityState.Added; int result = db.SaveChanges(); if (result > 1) { return result; } else { return 0; } } catch (Exception) { return 0; } }
public void SetGlobalQueryForTenant <T>(ModelBuilder builder) where T : class, ITenant { builder.Entity <T>() .HasQueryFilter(o => EF.Property <int>(o, "TenantId") == ClaimsHelper.GetClaim <int>(_http.User, "Tenant")); }
public List <DataEventRecord> GetDataEventRecords() { // Using the shadow property EF.Property<DateTime>(dataEventRecord) return(_context.DataEventRecords.OrderByDescending(dataEventRecord => EF.Property <DateTime>(dataEventRecord, "UpdatedTimestamp")).ToList()); }
protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); //strings for using SoftDelee in concret Tables modelBuilder.Entity <GroupsPermission>().Property <bool>("isDeleted"); modelBuilder.Entity <GroupsPermission>().HasQueryFilter(m => EF.Property <bool>(m, "isDeleted") == false); modelBuilder.Entity <UsersGroup>().Property <bool>("isDeleted"); modelBuilder.Entity <UsersGroup>().HasQueryFilter(m => EF.Property <bool>(m, "isDeleted") == false); modelBuilder.Entity <InvitesGroup>().Property <bool>("isDeleted"); modelBuilder.Entity <InvitesGroup>().HasQueryFilter(m => EF.Property <bool>(m, "isDeleted") == false); #region <!--strings to create a many-to-many relationships--> //GroupsPermission modelBuilder.Entity <GroupsPermission>() .HasKey(t => new { t.GroupId, t.PermissionId }); modelBuilder.Entity <GroupsPermission>() .HasOne(sc => sc.Group) .WithMany(s => s.GroupsPermissions) .HasForeignKey(sc => sc.GroupId); modelBuilder.Entity <GroupsPermission>() .HasOne(sc => sc.Permission) .WithMany(c => c.GroupsPermissions) .HasForeignKey(sc => sc.PermissionId); //UsersGroup modelBuilder.Entity <UsersGroup>() .HasKey(t => new { t.UserId, t.GroupId }); modelBuilder.Entity <UsersGroup>() .HasOne(sc => sc.User) .WithMany(s => s.UsersGroups) .HasForeignKey(sc => sc.UserId); modelBuilder.Entity <UsersGroup>() .HasOne(sc => sc.Group) .WithMany(c => c.UsersGroups) .HasForeignKey(sc => sc.GroupId); //InvitesGroup modelBuilder.Entity <InvitesGroup>() .HasKey(t => new { t.InviteId, t.GroupId }); modelBuilder.Entity <InvitesGroup>() .HasOne(sc => sc.Invite) .WithMany(s => s.InvitesGroups) .HasForeignKey(sc => sc.InviteId); modelBuilder.Entity <InvitesGroup>() .HasOne(sc => sc.Group) .WithMany(c => c.InvitesGroups) .HasForeignKey(sc => sc.GroupId); #endregion //strings to create a one-to-one relationships modelBuilder .Entity <Company>() .HasOne(u => u.Department) .WithOne(p => p.Company) .HasForeignKey <Department>(p => p.CompanyId); modelBuilder .Entity <Statuse>() .HasOne(u => u.Ticket) .WithOne(p => p.Statuse) .HasForeignKey <Ticket>(p => p.StatusId); modelBuilder .Entity <Priority>() .HasOne(u => u.Ticket) .WithOne(p => p.Priority) .HasForeignKey <Ticket>(p => p.PriorityId); modelBuilder .Entity <Template>() .HasOne(u => u.Ticket) .WithOne(p => p.Template) .HasForeignKey <Ticket>(p => p.TemplateId); modelBuilder .Entity <Group>() .HasOne(u => u.Template) .WithOne(p => p.Group) .HasForeignKey <Template>(p => p.GroupId); modelBuilder .Entity <Department>() .HasOne(u => u.User) .WithOne(p => p.Department) .HasForeignKey <User>(p => p.DepartmentId); modelBuilder .Entity <Comment>() .HasOne(u => u.Attachment) .WithOne(p => p.Comment) .HasForeignKey <Attachment>(p => p.CommentId); #region <!-- tables naming --> modelBuilder.Entity <Statuse>().ToTable("statuses"); modelBuilder.Entity <Permission>().ToTable("permissions"); modelBuilder.Entity <User>().ToTable("users"); modelBuilder.Entity <Priority>().ToTable("priorities"); modelBuilder.Entity <Company>().ToTable("companies"); modelBuilder.Entity <Group>().ToTable("groups"); modelBuilder.Entity <GroupsPermission>().ToTable("groups_permissions"); modelBuilder.Entity <UsersGroup>().ToTable("users_groups"); modelBuilder.Entity <Department>().ToTable("departments"); modelBuilder.Entity <Attachment>().ToTable("attachments"); modelBuilder.Entity <Invite>().ToTable("invites"); modelBuilder.Entity <InvitesGroup>().ToTable("invites_groups"); modelBuilder.Entity <Ticket>().ToTable("tickets"); modelBuilder.Entity <Comment>().ToTable("comments"); modelBuilder.Entity <TemplatesCategory>().ToTable("templates_categories"); modelBuilder.Entity <Template>().ToTable("templates"); #endregion }
public virtual void Where_bool_member_false_shadow() { AssertQuery <Product>(ps => ps.Where(p => !EF.Property <bool>(p, "Discontinued")), entryCount: 69); }
public virtual void Where_simple_shadow() { AssertQuery <Employee>( es => es.Where(e => EF.Property <string>(e, "Title") == "Sales Representative"), entryCount: 6); }
public static PropertyTagDTO MapFieldValues(EF.PropertyTag dbItem) { if (dbItem == null) return null; PropertyTagDTO retVal = new PropertyTagDTO() { Id = dbItem.Id, Name = dbItem.Name, Pin = dbItem.Pin }; return retVal; }
// GET: Students | with SortOrder paramater getting the query string action method paramater from URL. // All params will be null if page displayed for first time or hasn't clicked a paging or sorting link. public async Task <IActionResult> Index( string sortOrder, string currentFilter, string searchString, int?pageNumber) { //Provides the view with the current sort order. ViewData["CurrentSort"] = sortOrder; //If sortOrder param is null/empty, set NameSort param as descending. ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "LastName_desc" : ""; ViewData["DateSortParm"] = sortOrder == "EnrollmentDate" ? "EnrollmentDate_Desc" : "EnrollmentDate"; if (searchString != null) { pageNumber = 1; } else { searchString = currentFilter; } ViewData["CurrentFilter"] = searchString; var students = from s in _context.Students select s; if (!String.IsNullOrEmpty(searchString)) { students = students.Where(s => s.LastName.Contains(searchString) || s.FirstMidName.Contains(searchString)); } if (String.IsNullOrEmpty(sortOrder)) { sortOrder = "LastName"; } bool descending = false; if (sortOrder.EndsWith("_desc")) { sortOrder = sortOrder.Substring(0, sortOrder.Length - 5); descending = true; } if (descending) { students = students.OrderByDescending(e => EF.Property <object>(e, sortOrder)); } else { students = students.OrderBy(e => EF.Property <object>(e, sortOrder)); } int pageSize = 3; return(View(await PaginatedList <Student> .CreateAsync(students.AsNoTracking(), pageNumber ?? 1, pageSize))); }
public IList <UserNewsletter> GetUsersNewsletter() { return(_context.UsersNewsletter.OrderByDescending(userNewsletter => EF.Property <DateTime>(userNewsletter, "UpdatedTimestamp")).ToList()); }
public static void SetSoftDeleteFilter <TEntity>(this ModelBuilder modelBuilder) where TEntity : class { modelBuilder.Entity <TEntity>().HasQueryFilter(x => !EF.Property <bool>(x, "IsDeleted")); }
//取消选择所有记录 private void UnCheckAll(EF.EFDevGrid grid, GridView gridView) { for (int i = 0; i < gridView.RowCount; i++) { grid.SetSelectedColumnChecked(i, false); } gridView.Invalidate(); }
Tuple<Dictionary<string, HashSet<string>>, string, EF.Logo> GetChannel(XmlElement channel, int type, EF.RepositoryContext ctx, ref List<string> errors) { try { var file = channel.SelectSingleNode("File"); if (file != null) { var logoFileName = file.InnerText.Trim().Replace("\t", " "); var logoUrl = (type == 0 ? tbxTVLogosBaseUrl.Text : tbxRadioLogosBaseUrl.Text) + logoFileName; if (!string.IsNullOrEmpty(logoFileName)) { byte[] logoData = null; try { logoData = new System.Net.WebClient().DownloadData(logoUrl); } catch (Exception ex) { throw new Exception(string.Format("Error downloading logo '{0}' : {1}", logoFileName, ex.Message)); } using (MemoryStream ms = new MemoryStream(logoData)) { using (System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true, true)) { if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Png.Guid) { var aliases = new Dictionary<string, HashSet<string>>(); foreach (XmlElement item in channel.SelectNodes("Item")) { string name = item.GetAttribute("Name").Trim(); if (!string.IsNullOrEmpty(name)) { HashSet<string> providerNames = null; if (!aliases.TryGetValue(name, out providerNames)) providerNames = new HashSet<string>(); foreach (XmlElement provider in item.SelectNodes("Provider")) if (!string.IsNullOrWhiteSpace(provider.InnerText)) providerNames.Add(provider.InnerText.Trim()); foreach (XmlElement satellite in item.SelectNodes("Satellite")) if (!string.IsNullOrWhiteSpace(satellite.InnerText)) providerNames.Add(satellite.InnerText.Trim()); foreach (XmlElement place in item.SelectNodes("Place")) if (!string.IsNullOrWhiteSpace(place.InnerText)) providerNames.Add(place.InnerText.Trim()); aliases[name] = providerNames; } } if (aliases.Count > 0) { var logo = ctx.Logos.Create(); logo.Id = Guid.NewGuid(); logo.Name = System.IO.Path.GetFileNameWithoutExtension(logoFileName); logo.Width = image.Width; logo.Height = image.Height; logo.SizeInBytes = logoData.Length; logo.LastModified = DateTime.Now; logo.Origin = logoUrl; File.WriteAllBytes(Path.Combine(Server.MapPath("~/Logos"), logo.Id + ".png"), logoData); Thumbnailer.CreateLogoThumb(image, logo.Id); return new Tuple<Dictionary<string, HashSet<string>>, string, EF.Logo>(aliases, logoFileName, logo); } else { throw new Exception(string.Format("No aliases defined for logo '{0}'", logoFileName)); } } else { throw new Exception(string.Format("Logo '{0}' is not a valid PNG", logoFileName)); } } } } } } catch (Exception ex) { errors.Add(ex.Message); } return null; }
private bool isChange(EF.EFDevGrid grid) { grid.MainView.PostEditor(); grid.RefreshDataSource(); DataTable table = grid.DataSource as DataTable; if (table == null) return false; for (int rowIndex = 0; rowIndex < table.Rows.Count; ++rowIndex) { if (table.Rows[rowIndex].RowState == DataRowState.Deleted || table.Rows[rowIndex].RowState == DataRowState.Added || table.Rows[rowIndex].RowState == DataRowState.Modified) { return true; } } return false; }
static void AddTenantIdFilter <T, EntityKey>(ModelBuilder modelBuilder, ITenantProvider tenantProvider) where T : DomainEntity <EntityKey> { modelBuilder.Entity <T>().HasQueryFilter(entity => EF.Property <int>(entity, "TenantId") == tenantProvider.GetTenantId()); }
public static TUserId PropertyModifiedByUserId <TUserId>(object entity) => EF.Property <TUserId>(entity, ModifiedByUserId);
private Func <DbTestsContext, IEnumerable <OrderDetails> > CompiledQuery() => EF.CompileQuery((DbTestsContext context) => context.OrderDetails.ToList());
protected IEnumerable<T> QueryOutputTable<T>(DbContext context, string sqlQuery) where T : class { var compiled = EF.CompileQuery(GetQueryExpression<T>(sqlQuery)); var result = compiled(context); return result; }
/// <summary> /// Gets a list of assignments belonging to the specified user with pagination data /// </summary> /// <param name="userId">The is of the user who owns the assignments</param> /// <param name="searchString">The search string for the assignment title search</param> /// <param name="sortOrder">Specifies which column to sort by</param> /// <param name="descending">True returns a descending list, false returns an ascending list</param> /// <param name="onlyActiveAssignments">True returns only active assignments, false returns all assignments</param> /// <returns></returns> public IQueryable <Assignment> GetAssignmentsPagedList(int userId, string searchString, string sortOrder, bool descending, bool onlyActiveAssignments = false) { IQueryable <Assignment> assignments = Assignments.Where(c => c.Course.UserId == userId) .Include(a => a.Course); if (!string.IsNullOrEmpty(searchString)) { assignments = assignments.Where(c => c.Title.Contains(searchString)); } if (onlyActiveAssignments) { assignments = assignments.Where(c => c.DateCompleted == null); } assignments = descending ? assignments.OrderByDescending(e => EF.Property <object>(e, sortOrder)) : assignments.OrderBy(e => EF.Property <object>(e, sortOrder)); return(assignments); }
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<SampleModel>().Property<bool>("IsDeleted"); modelBuilder.Entity<SampleModel>().HasQueryFilter(m => EF.Property<bool>(m, "IsDeleted") == false); }
/// <summary> /// Gets a list of study sessions belonging to the specified user with pagination data /// </summary> /// <param name="userId">The id of the user who owns the study sessions</param> /// <param name="searchString">The search string for the study session search</param> /// <param name="sortOrder">Specifies which column to order by</param> /// <param name="descending">True returns a descending list, false returns an ascending list</param> /// <param name="onlyActiveStudySessions">True returns only planned (or active) study sessions, false returns all study sessions</param> /// <returns></returns> public IQueryable <StudySession> GetStudySessionsPagedList(int userId, string searchString, string sortOrder, bool descending, bool onlyActiveStudySessions = false) { IQueryable <StudySession> studySessions = GetStudySessionsByUser(userId, false) .Include(s => s.Course) .Include(s => s.StudySessionType); if (!string.IsNullOrEmpty(searchString)) { studySessions = studySessions.Where(s => s.Title.Contains(searchString)); } if (onlyActiveStudySessions) { studySessions = studySessions.Where(s => DateTime.Now.CompareTo(s.GetStudySessionStart().Add(s.Duration)) <= 0 && s.IsCompleted != true); } studySessions = descending ? studySessions.OrderByDescending(e => EF.Property <object>(e, sortOrder)) : studySessions.OrderBy(e => EF.Property <object>(e, sortOrder)); return(studySessions); }
public virtual void Where_simple_shadow_projection() { AssertQuery <Employee>( es => es.Where(e => EF.Property <string>(e, "Title") == "Sales Representative") .Select(e => EF.Property <string>(e, "Title"))); }
/// <summary> /// Gets a list of courses belonging to the specified user with pagination data. /// </summary> /// <param name="userId">The id of the user who owns the courses</param> /// <param name="searchString">The search string for the course title search</param> /// <param name="sortOrder">Specifies which column to sort by</param> /// <param name="descending">True returns a descending list, false returns an ascending list</param> /// <param name="onlyActiveCourses">True returns only active courses, false returns all courses</param> /// <returns></returns> public IQueryable <Course> GetCoursesPagedList(int userId, string searchString, string sortOrder, bool descending, bool onlyActiveCourses = false) { IQueryable <Course> courses = Courses.Where(c => c.UserId == userId); if (!string.IsNullOrEmpty(searchString)) { courses = courses.Where(c => c.Title.Contains(searchString)); } if (onlyActiveCourses) { courses = courses.Where(c => DateTime.Now.CompareTo(c.DateTo) <= 0); } courses = descending ? courses.OrderByDescending(e => EF.Property <object>(e, sortOrder)) : courses.OrderBy(e => EF.Property <object>(e, sortOrder)); return(courses); }
protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); builder.Entity <ToDoTask>().Property <bool>("IsDeleted"); builder.Entity <ToDoTask>().HasQueryFilter(m => EF.Property <bool>(m, "IsDeleted") == false); }
/// <summary> /// 根据ID找实体 /// </summary> /// <param name="id">实体id</param> /// <returns>实体</returns> public override LeaveMessage GetById(int id) { return(EF.CompileQuery((DataContext ctx, int cid) => ctx.LeaveMessage.Include(c => c.Children).ThenInclude(c => c.Children).ThenInclude(c => c.Children).FirstOrDefault(c => c.Id == cid))(DataContext, id)); }
private IEnumerable <Supplier> BaseQuery() { return(_context.Suppliers.OrderBy(b => EF.Property <DateTime>(b, NameOfCreatedField))); }
public virtual Task <bool> ExistsAsync(TKey key, CancellationToken cancellationToken = default) { return(DbSet.AnyAsync(x => EF.Property <TKey>(x, KeyField).Equals(key), cancellationToken)); }
public List <SourceInfo> GetSourceInfos(bool withChildren) { // Using the shadow property EF.Property<DateTime>(srcInfo) if (withChildren) { return(_context.SourceInfos.Include(s => s.DataEventRecords).OrderByDescending(srcInfo => EF.Property <DateTime>(srcInfo, "UpdatedTimestamp")).ToList()); } return(_context.SourceInfos.OrderByDescending(srcInfo => EF.Property <DateTime>(srcInfo, "UpdatedTimestamp")).ToList()); }
private IQueryable <GeekProfile> Sort(IQueryable <GeekProfile> profiles, OrderDirection orderDirection, string OrderBy) { return(orderDirection == OrderDirection.Asc ? profiles.OrderBy(p => EF.Property <object>(p, OrderBy)) : profiles.OrderByDescending(p => EF.Property <object>(p, OrderBy))); }
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.HasAnnotation("ProductVersion", "2.2.4-servicing-10062"); modelBuilder.Entity <OrderDetail>(entity => { entity.HasKey(e => e.OrderDetailId); entity.Property(e => e.OrderDetailId).HasColumnName("OrderDetailID"); entity.Property(e => e.ItemPrice).HasColumnType("money"); entity.Property(e => e.LinePrice).HasColumnType("money"); entity.Property(e => e.OrderId).HasColumnName("OrderID"); entity.Property(e => e.ProductId).HasColumnName("ProductID"); entity.HasOne(d => d.Order) .WithMany(p => p.OrderDetails) .HasForeignKey(d => d.OrderId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_OrderDetails_Orders"); entity.HasOne(d => d.Product) .WithMany(p => p.OrderDetails) .HasForeignKey(d => d.ProductId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_OrderDetails_Products"); }); modelBuilder.Entity <Order>(entity => { entity.HasKey(e => e.OrderId); entity.Property(e => e.OrderId).HasColumnName("OrderID"); entity.Property(e => e.OrderDate).HasColumnType("date"); entity.Property(e => e.TenantId).HasColumnName("TenantID"); }); modelBuilder.Entity <Product>(entity => { entity.HasKey(e => e.ProductId); entity.Property(e => e.ProductId).HasColumnName("ProductID"); entity.Property(e => e.Description).IsRequired(); entity.Property(e => e.ModelNumber) .IsRequired() .HasMaxLength(50); entity.Property(e => e.Name) .IsRequired() .HasMaxLength(100); entity.Property(e => e.Price).HasColumnType("money"); }); // Configure entity filter modelBuilder.Entity <Order>() .HasQueryFilter(o => EF.Property <int>(o, "TenantId") == ClaimsHelper.GetClaim <int>(_http.User, "Tenant")); SetGlobalQueryFilters(modelBuilder); }
protected override Expression <Func <TEntity, bool> > CreateFilterExpression <TEntity>() { var expression = base.CreateFilterExpression <TEntity>(); if (typeof(IHasLocalizableContent).IsAssignableFrom(typeof(TEntity))) { // HACK IHasCultureEntry 自动根据当前CultureInfo添加过滤器 Expression <Func <TEntity, bool> > cultureFilter = e => !IsCultureEntryFilterEnabled || EF.Property <string>(e, nameof(IHasLocalizableContent.CultureName)) == CurrentCultureName; // 当心变量捕获 expression = expression == null ? cultureFilter : CombineExpressions(expression, cultureFilter); } return(expression); }
public static TUserId PropertyCreatedByUserId <TUserId>(object entity) => EF.Property <TUserId>(entity, CreatedByUserId);
public static bool SetGridColumn(EF.EFDevGrid[] efGrid, string[] edFuncId) { int items = efGrid.Length < edFuncId.Length ? efGrid.Length : edFuncId.Length; if (items < 1) { return false; } try { string dll_path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\EFX.dll"; System.Reflection.Assembly assembly_EFX = System.Reflection.Assembly.LoadFrom(dll_path); Type myType = assembly_EFX.GetType("EFX.EFCGrid"); System.Reflection.MethodInfo InitSingleGridColumn_MethodInfo = myType.GetMethod("InitMultiGridColumn", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); if (InitSingleGridColumn_MethodInfo != null) { InitSingleGridColumn_MethodInfo.Invoke(null, new object[] { efGrid, edFuncId }); } } catch (Exception e) { EF.EFMessageBox.Show(e.Message); return false; } return true; /* EI.EIInfo inBlk = new EI.EIInfo(); inBlk.SetColName(1, "func_id"); int i = 0; for (i = 0; i < items; ++i) { inBlk.SetColVal(i + 1, "func_id", edFuncId[i]); } EI.EIInfo outBlk = EI.EITuxedo.CallService("eped54_inq_cfg1", inBlk); if (outBlk.GetSys().flag == 0) { try { string item_ename; string item_cname; string item_type; string item_len; string code_class; string form_edit_flag; string item_default_value; string item_hide_flag; DataSet DSsource = new DataSet(); DataTable dtsource = null; outBlk.GetBlockVal(DSsource); DevExpress.XtraGrid.Columns.GridColumn gridcolumn = null; DevExpress.XtraGrid.Views.Grid.GridView gridview = null; for (i = 0; i < items; ++i) { DataTable dt = new DataTable(); dt.TableName = edFuncId[i]; dtsource = DSsource.Tables[edFuncId[i]]; if (dtsource.Rows.Count < 1) { throw new Exception("Not found func_id :" + edFuncId[i]); } efGrid[i].BeginUpdate(); if (efGrid[i].MainView is DevExpress.XtraGrid.Views.Grid.GridView) { gridview = efGrid[i].MainView as DevExpress.XtraGrid.Views.Grid.GridView; gridview.Columns.Clear(); } else { efGrid[i].MainView.Dispose(); gridview = new DevExpress.XtraGrid.Views.Grid.GridView(efGrid[i]); efGrid[i].MainView = gridview; } gridview.BeginUpdate(); efGrid[i].Tag = dtsource; for (int row = 0; row < dtsource.Rows.Count; ++row) { item_hide_flag = dtsource.Rows[row]["item_hide_flag"].ToString().Trim(); item_ename = dtsource.Rows[row]["item_ename"].ToString().Trim(); item_cname = dtsource.Rows[row]["item_cname"].ToString().Trim(); item_type = dtsource.Rows[row]["item_type"].ToString().Trim(); item_len = dtsource.Rows[row]["item_len"].ToString().Trim(); code_class = dtsource.Rows[row]["code_class"].ToString().Trim(); form_edit_flag = dtsource.Rows[row]["form_edit_flag"].ToString().Trim(); item_default_value = dtsource.Rows[row]["item_default_value"].ToString().Trim(); gridcolumn = new DevExpress.XtraGrid.Columns.GridColumn(); gridview.Columns.Add(gridcolumn); gridcolumn.Caption = item_cname; gridcolumn.Name = item_ename; gridcolumn.FieldName = item_ename; gridcolumn.Visible = !("1" == item_hide_flag || "2" == item_hide_flag); if (gridcolumn.Visible) { gridcolumn.VisibleIndex = gridview.Columns.Count; } gridcolumn.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; gridcolumn.AppearanceHeader.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center; DataColumn col = dt.Columns.Add(item_ename); col.Caption = item_cname; if (item_type == "N") { if (item_len.Contains(",")) { col.DataType = typeof(double); if (item_default_value != string.Empty) { col.DefaultValue = double.Parse(item_default_value); } } else { col.DataType = typeof(int); if (item_default_value != string.Empty) { col.DefaultValue = int.Parse(item_default_value); } } if (item_default_value == string.Empty) { col.DefaultValue = 0; } gridcolumn.ColumnEdit = new DevExpress.XtraEditors.Repository.RepositoryItemCalcEdit(); } else if (item_type == "O" || item_type == "H") { DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit lookupedit = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit(); gridcolumn.ColumnEdit = lookupedit; lookupedit.DataSource = DSsource.Tables["CODECLASS:" + code_class]; lookupedit.AutoHeight = false; lookupedit.Name = "LookUpEdit_" + code_class; lookupedit.DisplayMember = lookupedit.ValueMember = "CODE"; if ("H" == item_type) { lookupedit.DisplayMember = "CODE_DESC_1_CONTENT"; } lookupedit.Properties.NullText = ""; col.DefaultValue = item_default_value; lookupedit.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("CODE", "����")); if (dtsource.Rows[row]["CODE_BIND_ENAME1"].ToString().Trim() == string.Empty && dtsource.Rows[row]["CODE_BIND_ENAME2"].ToString().Trim() == string.Empty && dtsource.Rows[row]["CODE_BIND_ENAME3"].ToString().Trim() == string.Empty && dtsource.Rows[row]["CODE_BIND_ENAME4"].ToString().Trim() == string.Empty && dtsource.Rows[row]["CODE_BIND_ENAME5"].ToString().Trim() == string.Empty) { //lookupedit.DisplayMember = "CODE_DESC_1_CONTENT"; lookupedit.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("CODE_DESC_1_CONTENT", "����")); } else { //lookupedit.DisplayMember = "CODE"; if (dtsource.Rows[row]["CODE_BIND_ENAME1"].ToString().Trim() != string.Empty) { lookupedit.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("CODE_DESC_1_CONTENT", "����1")); } if (dtsource.Rows[row]["CODE_BIND_ENAME2"].ToString().Trim() != string.Empty) { lookupedit.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("CODE_DESC_2_CONTENT", "����2")); } if (dtsource.Rows[row]["CODE_BIND_ENAME3"].ToString().Trim() != string.Empty) { lookupedit.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("CODE_DESC_3_CONTENT", "����3")); } if (dtsource.Rows[row]["CODE_BIND_ENAME4"].ToString().Trim() != string.Empty) { lookupedit.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("CODE_DESC_4_CONTENT", "����4")); } if (dtsource.Rows[row]["CODE_BIND_ENAME5"].ToString().Trim() != string.Empty) { lookupedit.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("CODE_DESC_5_CONTENT", "����5")); } lookupedit.EditValueChanged += new EventHandler(EF.CustomCols.SetGridColumn_lookupedit_EditValueChanged); } } else if (item_type == "F") // �������� { DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit buttedit = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit(); gridcolumn.ColumnEdit = buttedit; buttedit.Name = code_class; buttedit.Tag = code_class; col.DefaultValue = item_default_value; buttedit.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(EF.CustomCols.SetGridColumn_buttedit_ButtonClick); } else if ("D" == item_type) // ʱ������ { DevExpress.XtraEditors.Repository.RepositoryItemDateEdit dateEdit = new DevExpress.XtraEditors.Repository.RepositoryItemDateEdit(); gridcolumn.ColumnEdit = dateEdit; string strEditMask = dtsource.Rows[row]["editmask"].ToString().Trim(); if (strEditMask == string.Empty) { strEditMask = "yyyyMMdd"; } //dateEdit.EditMask = strEditMask; //dateEdit.Mask.UseMaskAsDisplayFormat = true; dateEdit.DisplayFormat.FormatString = strEditMask; dateEdit.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom; dateEdit.DisplayFormat.Format = new EF.CustomFormatter(); dateEdit.EditFormat.FormatString = strEditMask; //dateEdit.EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime; dateEdit.EditFormat.FormatType = DevExpress.Utils.FormatType.Custom; dateEdit.EditFormat.Format = new EF.CustomFormatter1(); dateEdit.ParseEditValue += new DevExpress.XtraEditors.Controls.ConvertEditValueEventHandler(dateEdit_ParseEditValue); //col.DataType = typeof(DateTime); //dateEdit.FormatEditValue += new DevExpress.XtraEditors.Controls.ConvertEditValueEventHandler(dateEdit_FormatEditValue); //col.DefaultValue = ""; } else if ("B" == item_type) // ���� { col.DataType = typeof(Boolean); gridcolumn.ColumnEdit = new DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit(); if ("1" == item_default_value || "true" == item_default_value.ToLower()) { col.DefaultValue = true; } else { col.DefaultValue = false; } } else { col.DataType = typeof(string); gridcolumn.ColumnEdit = new DevExpress.XtraEditors.Repository.RepositoryItemTextEdit(); col.DefaultValue = item_default_value; } gridcolumn.ColumnEdit.Leave += new EventHandler(EF.CustomCols.CustomGridColumnEdit_Leave); //gridcolumn.ColumnEdit.EditValueChanged += new EventHandler(EF.CustomCols.CustomGridColumnEdit_EditValueChanged); if (form_edit_flag == "0") { gridcolumn.ColumnEdit.ReadOnly = true; } } dt.Rows.Add(); efGrid[i].ShowSelectionColumn = efGrid[i].ShowSelectionColumn; efGrid[i].ShowSelectedColumn = efGrid[i].ShowSelectedColumn; efGrid[i].DataSource = dt; gridview.BestFitColumns(); gridview.EndUpdate(); efGrid[i].EndUpdate(); } return true; } catch (Exception e) { //MessageBox.Show(e.Message); } } return false; */ }
public static TTenantId PropertyTenantId <TTenantId>(object entity) => EF.Property <TTenantId>(entity, TenantId);
public async Task <IList <object> > GetUsers(int page = 1, int limit = 5, string sort = "Id", string search = "") { var skip = (page - 1) * limit; if (search == "") { var users = _context.UserModels.OrderBy(p => EF.Property <object>(p, sort)); return(await users.Skip(skip).Take(limit).ToArrayAsync()); } else { var users = _context.UserModels.Where(p => p.Id.ToString().Contains(search) || p.Name.Contains(search) || p.Email.Contains(search) || p.Comments.Contains(search) || p.Choice.Contains(search)).OrderBy(p => EF.Property <object>(p, sort)); //True version return(await users.Skip(skip).Take(limit).ToArrayAsync()); } }
EF.Suggestion GetSuggestion(EF.RepositoryContext ctx) { Guid suggestionId = GetSuggestionIdFromRequest(); if (suggestionId != Guid.Empty) { return ctx.Suggestions .Include("Channels") .Include("Messages") .Include("Aliases") .Include("Aliases.Channel") .Include("Aliases.Channel.Logos") .Include("Aliases.Channel.Aliases") .Include("Logos").Include("Logos.Channels").Include("Logos.Channels.Logos") .FirstOrDefault(s => s.Id == suggestionId); } return null; }
public async Task <List <UserDomain> > GetAllUsers(UserQueryParam userQueryParam) { // Search search term to use (searches on [name] column for the MVP) // Sort the column name by which to sort // Direction sort order; asc, desc // Limit maximum number of records to return // Offset number of records to skip for pagination List <UserDomain> response = new List <UserDomain>(); var direction = ConvertToEnum(userQueryParam.Direction); if (direction == SortDirection.None) { throw new UseCaseException() { UserErrorMessage = "The sort direction was not valid (must be one of asc, desc)" } } ; var matchingUsers = Context.Users.AsQueryable() .Where(u => u.Status.ToLower() != "deleted"); // handle search if (!string.IsNullOrWhiteSpace(userQueryParam.Search)) { matchingUsers = matchingUsers.Where(u => EF.Functions.ILike(u.Name, $"%{userQueryParam.Search}%") || EF.Functions.ILike(u.Email, $"%{userQueryParam.Search}%")); } // handle sort by column name and sort direction var entityPropName = GetEntityPropertyForColumnName(typeof(User), userQueryParam.Sort); if (entityPropName == null) { throw new UseCaseException() { UserErrorMessage = $"The 'Sort' parameter contained the value '{userQueryParam.Sort}' " + "which is not a valid column name" } } ; matchingUsers = (direction == SortDirection.Asc) ? matchingUsers.OrderBy(u => EF.Property <User>(u, entityPropName)) : matchingUsers.OrderByDescending(u => EF.Property <User>(u, entityPropName)); // handle pagination options if (userQueryParam.Offset.HasValue) { matchingUsers = matchingUsers.Skip(userQueryParam.Offset.Value); } if (userQueryParam.Limit.HasValue) { matchingUsers = matchingUsers.Take(userQueryParam.Limit.Value); } try { var userList = await matchingUsers .Include(u => u.UserOrganisations) .ThenInclude(uo => uo.Organisation) .Include(uo => uo.Organisations) .Include(u => u.UserRoles) .ThenInclude(ur => ur.Role) .AsNoTracking() .ToListAsync() .ConfigureAwait(false); response = _mapper.ToDomain(userList); } catch (InvalidOperationException e) { throw new UseCaseException() { UserErrorMessage = "Could not run the user search query with the supplied input parameters", DevErrorMessage = e.Message }; } return(response); }
public virtual async Task Where_DateOnly_ctor(bool async) { await AssertQuery( async, ss => ss.Set <Mission>().Where(m => new DateOnly(EF.Property <DateOnly>(m, "Date").Year, EF.Property <DateOnly>(m, "Date").Month, 1) == new DateOnly(1996, 9, 11))); AssertSql( @"SELECT m.""Id"", m.""CodeName"", m.""Date"", m.""Duration"", m.""Rating"", m.""Time"", m.""Timeline"" FROM ""Missions"" AS m WHERE make_date(date_part('year', m.""Date"")::INT, date_part('month', m.""Date"")::INT, 1) = DATE '1996-09-11'"); }
void CreateDbChannel(Tuple<Dictionary<string, HashSet<string>>, string, EF.Logo> importChannel, ChannelType channelType, EF.RepositoryContext ctx, EF.Repository repo, EF.User user, Dictionary<string, EF.Provider> knownProviders) { var channel = ctx.Channels.Create(); channel.Id = Guid.NewGuid(); channel.Type = channelType; channel.Name = importChannel.Item1.First().Key; channel.RegionCode = ddlChannelRegion.SelectedValue; repo.Channels.Add(channel); var logo = importChannel.Item3; logo.Creator = user; repo.Logos.Add(logo); channel.Logos.Add(logo); logo.Channels.Add(channel); foreach (var newAlias in importChannel.Item1) { var alias = ctx.Aliases.Create(); alias.Created = DateTime.Now; alias.Id = Guid.NewGuid(); alias.Name = newAlias.Key; channel.Aliases.Add(alias); foreach (var aProvider in newAlias.Value) { EF.Provider provider = null; if (!knownProviders.TryGetValue(aProvider, out provider)) { provider = ctx.Providers.Create(); provider.Id = Guid.NewGuid(); provider.Name = aProvider; repo.Providers.Add(provider); knownProviders.Add(aProvider, provider); } alias.Providers.Add(provider); provider.Aliases.Add(alias); } } }