protected override Result ExecuteCore() { var order = RF.Find <PurchaseOrder>().GetById(this.OrderId) as PurchaseOrder; if (order == null) { throw new ArgumentNullException("order"); } if (order.StorageInStatus != OrderStorageInStatus.Waiting) { return("该订单已经完全入库,操作失败。"); } //生成入库单 var storageIn = new OrderStorageInBill { Order = order, Code = order.Code + " - 入库", Date = DateTime.Now, Comment = "系统生成" }; //默认直接入库第一个仓库 storageIn.Storage = RF.ResolveInstance <StorageRepository>().CacheAll().First() as Storage; //调用另外一个服务直接入库 var siService = ServiceFactory.Create <AddOrderStorageInBillService>(); siService.Item = storageIn; siService.Invoke(); return(siService.Result); }
protected override void Up() { this.RunCode((Action<Rafy.Data.IDbAccesser>)(db => { //由于本类没有支持 Down 操作,所以这里面的 Up 需要防止重入。 var repo = RF.ResolveInstance<PersonRepository>(); var list = repo.GetAll(); if (list.Count == 0) { list.Add(new Person { Name = "胡庆访", IsDefault = true }); var tagRepo = RF.Find<Tag>(); var tagList = tagRepo.NewList(); tagList.Add(new Tag { Name = "衣" }); tagList.Add(new Tag { Name = "食" }); tagList.Add(new Tag { Name = "住" }); tagList.Add(new Tag { Name = "行" }); tagList.Add(new Tag { Name = "人情" }); tagList.Add(new Tag { Name = "公司" }); tagList.Add(new Tag { Name = "工资" }); using (var tran = RF.TransactionScope(repo)) { repo.Save(list); tagRepo.Save(tagList); tran.Complete(); } } })); }
/// <summary> /// 执行查询操作。 /// <remarks>可能执行本地查询,也可能是远程查询。</remarks> /// </summary> /// <param name="resultView"></param> private void FireQuery(LogicalView resultView) { var args = new QueryEventArgs { ResultView = resultView }; this.OnQuerying(args); //如果是本地查询模式,则尝试为 ListLogicalView 进行过滤。 var criteria = this.Current; if (criteria.CanLocalFilter) { var listView = resultView as ListLogicalView; if (listView != null) { listView.Filter = criteria.LocalFilter; this.OnQueryCompleted(args); return; } } //需要复制一个查询对象,这样可以保存下当前的查询值, //否则会造成 ReloadDataAsync 方法查询时不是使用当前的这些值来查询。 var queryCriteria = Entity.New(this.EntityType); queryCriteria.Clone(this.Current, CloneOptions.NewComposition()); //导航面板的查询使用隐式查询。 resultView.DataLoader.LoadDataAsync( () => RF.Find(resultView.EntityType).GetBy(queryCriteria), () => this.OnQueryCompleted(args) ); }
/// <summary> /// 实体的自定义反序列化方法。 /// </summary> /// <param name="type">The type.</param> /// <param name="jObject">The j object.</param> /// <param name="id">实体的标识。如果已经在 jObject 中指定时,此参数可以传入 null。</param> /// <returns></returns> public Entity DeserializeEntity(Type type, JObject jObject, object id) { Entity entity = null; if (id != null) { if (_creationMode == UpdatedEntityCreationMode.RequeryFromRepository) { var repository = RF.Find(type); entity = repository.GetById(id); } else { entity = Activator.CreateInstance(type) as Entity; entity.PersistenceStatus = PersistenceStatus.Unchanged; } } if (entity == null) { entity = Activator.CreateInstance(type) as Entity; } //反序列化一般属性 DeserializeProperties(jObject, entity); return(entity); }
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) { /*********************** 代码块解释 ********************************* * 如果要绑定的模型是一个实体,而且已经提供了这个实体的Id,说明是在对旧实体的更新, * 这时需要把旧实体从数据库中获取出来再设置新的值。这样可以解决两个问题: * * 在更新时,不需要再主动设置实体的 PersistenceStatus 为 Modified。 * * 在更新树节点时,不会因为在 TreePId 没有变化的情况下更新 TreePId,而造成 TreeIndex 出错的问题。 **********************************************************************/ if (modelType.IsSubclassOf(typeof(Entity)) && !string.Equals(controllerContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) { var idValue = bindingContext.ValueProvider.GetValue(Entity.IdProperty.Name); if (idValue != null) { var id = (string)idValue.ConvertTo(typeof(string)); if (!string.IsNullOrWhiteSpace(id)) { var repository = RF.Find(modelType); var entity = repository.GetById(id); if (entity != null) { return(entity); } } } } return(base.CreateModel(controllerContext, bindingContext, modelType)); }
protected override void Up() { this.RunCode(db => { //由于本类没有支持 Down 操作,所以这里面的 Up 需要防止重入。 var repo = RF.Find <Storage>(); var list = repo.GetAll(); if (list.Count == 0) { repo.Save(new Storage { Code = "20120423-0001", Name = "北京仓库", Address = "北京", ResponsiblePerson = "胡庆访", Area = "海淀区", IsDefault = true }); repo.Save(new Storage { Code = "20120425-0002", Name = "云南仓库", Address = "云南省", ResponsiblePerson = "胡庆访", Area = "昭通市" }); } }); }
private List <EntityMeta> GetMappingEntityTypes() { var tableEntityTypes = new List <EntityMeta>(); //程序集列表,生成数据库会反射找到程序集内的实体类型进行数据库映射 foreach (var assembly in RafyEnvironment.AllPlugins) { foreach (var type in assembly.Assembly.GetTypes()) { if (!type.IsAbstract) { //判断实体类型是否映射了某一个数据库 var em = CommonModel.Entities.Find(type); if (em != null && em.TableMeta != null) { var entityDb = RdbDataProvider.Get(RF.Find(type)).ConnectionStringSettingName; if (entityDb == this._dbSetting.Name) { tableEntityTypes.Add(em); } } } } } return(tableEntityTypes); }
/// <summary> /// 反序列化指定的数组为一个实体的列表。 /// </summary> /// <param name="listType"></param> /// <param name="jArray"></param> /// <returns></returns> public EntityList DeserializeList(Type listType, JArray jArray) { var entityType = EntityMatrix.FindByList(listType).EntityType; var repo = RF.Find(entityType); //构造或查询出数据对应的实体列表。 EntityList list = null; if (_creationMode == UpdatedEntityCreationMode.RequeryFromRepository) { //先从数据库中找出所有提供了 Id 的实体。 var idList = jArray.Cast <JObject>().Select(item => TryGetId(item)) .Where(id => id != null).ToArray(); list = repo.GetByIdList(idList); } else { list = repo.NewList(); } //依次反序列化数组中的实体: //如果有 Id,则在数据库中查询出的列表 list 中查找出对应的实体,然后反序列化值。否则,直接构造新实体。 for (int i = 0, c = jArray.Count; i < c; i++) { var jEntity = jArray[i] as JObject; var child = FindOrCreate(list, jEntity); DeserializeProperties(jEntity, child); } return(list); }
private void AsyncLoadPositions(ViewModel[] viewModels) { AsyncHelper.InvokeSafe(() => { foreach (var model in viewModels) { var positions = (RF.Find <OrgPosition>() as OrgPositionRepository) .GetList(model.UserId).Cast <OrgPosition>().ToList(); if (positions.Count > 0) { var positionResult = new StringBuilder(); for (int i = 0, c = positions.Count; i < c; i++) { var item = positions[i]; if (i != 0) { positionResult.Append('/'); } positionResult.Append(item.View_Name); } model.Position = positionResult.ToString(); } } }); }
/// <summary> /// 加载数据 /// /// 如果已经初始化CslaDataProvider,则从里面获取数据。 /// 否则表示 /// </summary> /// <param name="async"> /// 是否使用异步模式 /// </param> private void EnsureDataLoaded(bool async) { if (this.IsUseLocalData()) { //本地时,每次都检测属性的值是否是最新的。 this.RefreshPropertyDataSource(); } else { if (this._listView.Data == null) { if (async) { this._listView.DataLoader.LoadDataAsync(() => { using (this._process.TryEnterProcess(LLPEProcess.AsyncDataLoaded)) { this.SyncValueToSelection(); } }); } else { this._listView.Data = RF.Find(this._listView.EntityType).CacheAll(); } } } }
/// <summary> /// 根据物料大类代码查找物料大类 /// </summary> /// <param name="code"></param> /// <returns></returns> private ItemLargeCategory FindLargeCategoryByCode(string code) { var categoryRepo = RF.Find <ItemLargeCategory>(); var categoryQueryer = categoryRepo.CreateEntityQueryer <ItemLargeCategory>(); categoryQueryer.Where(f => f.Code == code); return(categoryRepo.QueryFirst(categoryQueryer) as ItemLargeCategory); }
private void TrySetProperty(Entity e, string pName, JToken value) { //有些小写的客户端数据被传输到了服务端,需要被过滤掉。 if (char.IsLower(pName[0])) { return; } var pm = _entityMeta.Property(pName) as PropertyMeta ?? _entityMeta.ChildrenProperty(pName); if (pm != null) { var mp = pm.ManagedProperty; if (mp is IListProperty) { //todo: 此处的性能可能需要优化,聚合保存子列表时,重复的查询 Repository var entityType = EntityMatrix.FindByList(pm.PropertyType).EntityType; var repo = RF.Find(entityType); //列表属性的设置不能使用 SetProperty,否则,list.Parent 将会无值。 //但是也不能直接使用 LoadProperty,否则会导致调用 list.MarkOld,从而不会保存这个列表。 //所以只能先装载一个空列表,然后再把 json 中的数据转换为实体加入到这个列表中。 var list = repo.NewList(); e.LoadProperty(mp, list); ListReader.JsonToEntity(value as JObject, repo, list); } else { var rawValue = (value as JValue).Value; rawValue = EntityJsonConverter.ToServerValue(pm.PropertyType, rawValue); e.SetProperty(mp, rawValue, ManagedPropertyChangedSource.FromUIOperating); } } else { var rawValue = (value as JValue).Value; //如果没有找到一般的属性,则尝试查找外键属性 for (int i = 0, c = _refIdProperties.Count; i < c; i++) { var rip = _refIdProperties[i]; if (rip.Name == pName) { e.SetRefId(rip, rawValue); break; } } //只读属性。 //if(notFound) //{ // throw new InvalidOperationException("没有在实体中找到这个属性:" + pName); //} } }
public void MPT_ORM_PropertiesMapping_Inheritance() { var repo = RF.Find <TestAdministrator>() as TestUserRepository; //清空历史数据 var user = repo.GetByName("huqf"); if (user != null) { user.PersistenceStatus = PersistenceStatus.Deleted; repo.Save(user); } //新建用户并设置一些值。 var user1 = repo.New().CastTo <TestAdministrator>(); user1.Name = "huqf"; user1.Level = 1; TestUserExt.SetUserCode(user1, "NewUserCode"); //为用户添加一个角色 var userRoles = user1.TestRoleList; var role = new TestRole(); userRoles.Add(role); role.Name = "admin"; Assert.AreEqual(user1.Id, role.TestUserId); //保存新建用户 repo.Save(user1); //重新获取保存的用户 var user2 = repo.GetByName("huqf").CastTo <TestAdministrator>(); Assert.IsNotNull(user2); Assert.AreEqual(user1.Name, user2.Name); Assert.AreEqual(user2.Level, 1); Assert.AreEqual(TestUserExt.GetUserCode(user2), "NewUserCode"); Assert.AreEqual(user1.TestRoleList.Count, 1); Assert.AreEqual(user1.TestRoleList[0].CastTo <TestRole>().Name, "admin"); //获取 Role var role2 = RF.Find <TestRole>().GetById(role.Id).CastTo <TestRole>(); Assert.AreEqual(role.Name, "admin"); Assert.AreEqual(role2.Name, "admin"); Assert.AreEqual(user1.Id, role2.TestUserId); Assert.IsNotNull(role2.TestUser); //删除用户 user1.PersistenceStatus = PersistenceStatus.Deleted; repo.Save(user1); var users = repo.GetAll(); Assert.IsTrue(!users.Cast <TestUser>().Any(u => u.Name == "huqf")); }
/// <summary> /// 清空所有版本号,所有缓存都会过期。 /// </summary> public void Clear() { var cacheRepo = RF.Find <ScopeVersion>(); var allList = cacheRepo.GetAll(); allList.Clear(); cacheRepo.Save(allList); }
public void MPT_WPFBinding() { var userList = RF.Find <TestUser>().NewList(); var newUser = Get <TestUser>(); newUser.Name = "1"; userList.Add(newUser); //创建 binding view var view = CollectionViewSource.GetDefaultView(userList) as ListCollectionView; Assert.IsNotNull(view); var userListView = view.SourceCollection as TestUserList; Assert.AreEqual(userListView, userList); //list change 事件 NotifyCollectionChangedEventArgs eventArgs = null; userListView.CollectionChanged += (oo, ee) => { eventArgs = ee; }; newUser = Get <TestUser>(); newUser.Name = "2"; userList.Add(newUser); Assert.IsNotNull(eventArgs); Assert.AreEqual(eventArgs.Action, NotifyCollectionChangedAction.Add); Assert.AreEqual(userListView.Count, userList.Count); //测试 ICustomTypeDescriptor 的实现 var newUserView = userListView[1]; var properties = (newUserView as ICustomTypeDescriptor).GetProperties(); var managedProperties = newUser.PropertiesContainer.GetAvailableProperties(); Assert.IsTrue(managedProperties.All(mp => properties.Cast <PropertyDescriptor>().Any(p => p.Name == mp.Name))); //去掉索引器 var clrProperties = typeof(TestUser).GetProperties().Where(p => p.GetMethod.GetParameters().Length == 0).ToArray(); Assert.IsTrue(clrProperties.All(clr => properties.Cast <PropertyDescriptor>().Any(p => p.Name == clr.Name))); //view model 的属性更改事件 var namePropertyChanged = false; newUserView.PropertyChanged += (oo, ee) => { if (ee.PropertyName == "Name") { namePropertyChanged = true; } }; newUser.Name += "_Modified"; Assert.IsTrue(namePropertyChanged); }
protected override void Up() { this.RunCode(db => { var repo = RF.Find <TestUser>(); for (int i = 0; i < 10; i++) { var user = new TestUser(); repo.Save(user); } }); }
protected override void Down() { this.RunCode(db => { var repo = RF.Find <TestUser>(); var all = repo.GetAll(); foreach (var user in all) { user.PersistenceStatus = PersistenceStatus.Deleted; } repo.Save(all); }); }
public DataPortalResult Action(Type objectType, string methodName, object criteria, DataPortalContext context) { var obj = RF.Find(objectType); var res = MethodCaller.CallMethodIfImplemented(obj, methodName, criteria); if (res != null) { return(new DataPortalResult(res)); } else { return(new DataPortalResult(obj)); } }
public void ET_Repository_CantHasNoRepo() { bool success = false; try { var repo = RF.Find <NoRepoEntity>(); success = true; } catch (TypeInitializationException) { } Assert.IsFalse(success, "没有编写仓库类型的实体,获取其相应的仓库时应该报错。"); }
public void DMT_ManualMigrate() { using (var context = new RafyDbMigrationContext(UnitTestEntityRepositoryDataProvider.DbSettingName)) { context.HistoryRepository = new DbHistoryRepository(); context.RunDataLossOperation = DataLossOperation.All; try { context.ManualMigrations.Clear(); context.ManualMigrations.Add(new DMT_ManualMigrateEntity()); context.ManualMigrations.Add(new DMT_ManualMigrateTest()); //手工更新 context.MigrateManually(); //历史记录 var histories = context.GetHistories(); Assert.IsTrue(histories.Count == 2); Assert.IsTrue(histories[0] is DMT_ManualMigrateTest); Assert.IsTrue(histories[1] is DMT_ManualMigrateEntity); //数据库结构 var database = context.DatabaseMetaReader.Read(); var table = database.FindTable("TestingTable"); Assert.IsTrue(table.Columns.Count == 2); var pk = table.FindPrimaryColumn(); Assert.IsTrue(pk.Name.EqualsIgnoreCase("Id")); Assert.IsTrue(pk.DbType == DbType.Int32); //数据库数据 using (var db = DbAccesserFactory.Create(context.DbSetting)) { var rows = db.QueryDataTable("select * from TestingTable"); Assert.IsTrue(rows.Rows.Count == 2); } var repo = RF.Find <TestUser>(); Assert.IsTrue(repo.CountAll() == 10); } finally { //回滚 context.RollbackAll(RollbackAction.DeleteHistory); var database = context.DatabaseMetaReader.Read(); Assert.IsTrue(database.FindTable("TestingTable") == null); } } }
protected override Result ExecuteCore() { var orgPosition = RF.Find <OrgPosition>().GetById(this.OrgPositionId) as OrgPosition; if (orgPosition == null) { return("没有找到对应的岗位。"); } var curModule = RF.Find <ModuleAC>().GetById(this.ModuleId) as ModuleAC; var moduleKey = curModule.KeyLabel; var ids = this.DenyOperationIds.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) .Select(strId => Convert.ToInt32(strId)).ToArray(); //清空当前模块在 denyList 中的数据 var denyList = orgPosition.OrgPositionOperationDenyList; var moduleOperations = denyList.Cast <OrgPositionOperationDeny>().Where(d => d.ModuleKey == moduleKey).ToArray(); foreach (var item in moduleOperations) { denyList.Remove(item); } //根据当前的选择项把数据重新加入到 denyList 中。 var toDeny = ids.Select(id => curModule.OperationACList.FirstOrDefault(op => op.Id.Equals(id))) .Where(op => op != null).ToArray(); var moduleScopeTranslated = OperationAC.ModuleScope.Translate(); foreach (OperationAC item in toDeny) { var deny = new OrgPositionOperationDeny { ModuleKey = moduleKey, OperationKey = item.OperationKey }; if (item.ScopeKeyLabel != moduleScopeTranslated) { deny.BlockKey = item.ScopeKeyLabel; } denyList.Add(deny); } //保存到数据库中。 RF.Save(orgPosition); return(new Result(true, "权限保存成功。")); }
public override void Execute(ListLogicalView view) { var list = RF.Find <UserLoginLog>().GetAll() .OfType <UserLoginLog>() .ToList(); var control = new LoginLogStatistic(list); App.Windows.ShowDialog(control, w => { w.Title = "登录时间统计".Translate(); w.MinHeight = 300; w.SizeToContent = SizeToContent.WidthAndHeight; }); }
internal void LoadChildrenProperties() { if (this.User != null) { this.Id = this.User.Id; this.Code = this.User.Code; this.Name = this.User.Name; this.IsAuthenticated = true; this._roles = (RF.Find <OrgPosition>() as OrgPositionRepository).GetList(User.Id); // list of roles from security store } else { this.Id = 0; this.IsAuthenticated = false; this._roles = null; } }
/// <summary> /// 通过指定的数据获取方法,异步加载该视图对应实体类型的指定实体对象 /// </summary> /// <param name="dataProvider">自定义数据提供程序。可以返回 Entity,也可以返回 EntityList。</param> /// <param name="changedCallback">数据加载返回后的回调函数</param> public void LoadDataAsync(Func <IDomainComponent> dataProvider, Action changedCallback) { if (dataProvider == null) { dataProvider = () => RF.Find(this._view.EntityType).CacheAll(); } using (this._dataProvider.DeferRefresh()) { this._dataProvider.DataProducer = dataProvider; } if (changedCallback != null) { this.ListenDataChangedOnce(changedCallback); } }
protected override void Validate(Entity entity, RuleArgs e) { var id = entity.Id; var repo = RF.Find(ReferenceProperty.Owner); if (repo != null) { var criteria = new CommonQueryCriteria(); criteria.Add(ReferenceProperty.Property, id); var count = repo.CountBy(criteria); if (count > 0) { e.BrokenDescription = this.BuildError(entity, count); } } }
protected override Result ExecuteCore() { var orderId = this.ItemId; var osibRepo = RF.ResolveInstance <OrderStorageInBillRepository>(); var storageInList = osibRepo.GetByOrderId(orderId); if (storageInList.Count > 0) { return("该定单已经有相应的入库记录,不能直接删除。"); } var order = RF.Find <PurchaseOrder>().GetById(orderId); order.PersistenceStatus = PersistenceStatus.Deleted; RF.Save(order); return(true); }
/// <summary> /// 实体的自定义反序列化方法。 /// </summary> /// <param name="type">The type.</param> /// <param name="jObject">The j object.</param> /// <param name="id">实体的标识。如果已经在 jObject 中指定时,此参数可以传入 null。</param> /// <returns></returns> public Entity DeserializeEntity(Type type, JObject jObject, object id) { Entity entity = null; if (id != null) { var repository = RF.Find(type); entity = repository.GetById(id); } if (entity == null) { entity = Activator.CreateInstance(type) as Entity; } //反序列化一般属性 DeserializeProperties(jObject, entity); return(entity); }
public void MPT_ORM_PropertiesMapping() { using (RF.TransactionScope(UnitTestEntityRepositoryDataProvider.DbSettingName)) { var repo = RF.ResolveInstance <TestUserRepository>(); //新建用户并设置一些值。 var user1 = repo.New(); user1.Name = "huqf"; TestUserExt.SetUserCode(user1, "NewUserCode"); //为用户添加一个角色 var userRoles = user1.TestRoleList; var role = new TestRole(); userRoles.Add(role); role.Name = "admin"; Assert.AreEqual(user1.Id, role.TestUserId); //保存新建用户 repo.Save(user1); //重新获取保存的用户 var user2 = repo.GetByName("huqf"); Assert.IsNotNull(user2); Assert.AreEqual(user1.Name, user2.Name); Assert.AreEqual(TestUserExt.GetUserCode(user2), "NewUserCode"); Assert.AreEqual(user1.TestRoleList.Count, 1); Assert.AreEqual(user1.TestRoleList[0].CastTo <TestRole>().Name, "admin"); //获取 Role var role2 = RF.Find <TestRole>().GetById(role.Id).CastTo <TestRole>(); Assert.AreEqual(role.Name, "admin"); Assert.AreEqual(role2.Name, "admin"); Assert.AreEqual(user1.Id, role2.TestUserId); Assert.IsNotNull(role2.TestUser); //删除用户 user1.PersistenceStatus = PersistenceStatus.Deleted; repo.Save(user1); var users = repo.GetAll(); Assert.IsTrue(!users.Cast <TestUser>().Any(u => u.Name == "huqf")); } }
private EntityList DeserializeList(Type listType, JArray jArray) { var entityType = EntityMatrix.FindByList(listType).EntityType; var repo = RF.Find(entityType); //先从数据库中找出所有提供了 Id 的实体。 var idList = jArray.Cast <JObject>().Select(item => TryGetId(item)) .Where(id => id != null).ToArray(); var list = repo.GetByIdList(idList); //依次反序列化数组中的实体: //如果有 Id,则在数据库中查询出的列表 list 中查找出对应的实体,然后反序列化值。否则,直接构造新实体。 foreach (JObject jEntity in jArray) { var child = FindOrCreate(list, jEntity); DeserializeProperties(jEntity, child); } return(list); }
public void ET_Repository_Simple() { var pbsRepository = RF.Find <PBS>(); using (RF.TransactionScope(pbsRepository)) { pbsRepository.Save(new PBSType { Name = "PBSType1", PBSList = { new PBS { Name = "PBS1" }, new PBS { Name = "PBS2" }, new PBS { Name = "PBS3" }, new PBS { Name = "PBS4" }, new PBS { Name = "PBS5" }, } }); var pbss = pbsRepository.GetAll(); if (pbss.Count > 0) { var pbsOriginal = pbss[0] as PBS; var pbs = pbsRepository.GetById(pbsOriginal.Id) as PBS; Assert.IsNotNull(pbs); Assert.AreEqual(pbs.Id, pbsOriginal.Id); Assert.AreEqual(pbs.PBSTypeId, pbsOriginal.PBSTypeId); Assert.AreEqual(pbs.Name, pbsOriginal.Name); } } }