• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# UnitOfWork类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中UnitOfWork的典型用法代码示例。如果您正苦于以下问题:C# UnitOfWork类的具体用法?C# UnitOfWork怎么用?C# UnitOfWork使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



UnitOfWork类属于命名空间,在下文中一共展示了UnitOfWork类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: FrmCrearTipoEmpleado

 public FrmCrearTipoEmpleado(TipoEmpleado tipoempleado, XPCollection xpcTipoEmpleado, UnitOfWork uow)
     : this()
 {
     this.TipoEmpleado = tipoempleado;
     this.uow = uow;
     this.xpcTipoEmpleado = xpcTipoEmpleado;
 }
开发者ID:jmurataya,项目名称:Nomina,代码行数:7,代码来源:FrmCrearTipoEmpleado.cs


示例2: Application_PostAuthenticateRequest

        protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
        {
            if (FormsAuthentication.CookiesSupported != true) return;
            if (Request.Cookies[FormsAuthentication.FormsCookieName] == null) return;

            //let us take out the username now
            var formsAuthenticationTicket = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value);
            if (formsAuthenticationTicket == null) return;

            var username = formsAuthenticationTicket.Name;
            var roles = String.Empty;

            using (IDataContextAsync context = new OIDataContext())
            using (IUnitOfWorkAsync unitOfWork = new UnitOfWork(context))
            {
                IRepositoryAsync<Account> accountRepository = new Repository<Account>(context, unitOfWork);
                var user =
                    accountRepository.Query(u => u.Username == username).Include(r => r.Role).Select().SingleOrDefault();

                if (user != null) roles = user.Role.RoleType;
            }

            //Let us set the Pricipal with our user specific details
            HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
                new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
        }
开发者ID:jeffjuarez,项目名称:OI---All-Charts,代码行数:26,代码来源:Global.asax.cs


示例3: UpdateDatabaseBeforeUpdateSchema

        public override void UpdateDatabaseBeforeUpdateSchema() {
            base.UpdateDatabaseBeforeUpdateSchema();
            if (CurrentDBVersion > new Version(0, 0, 0, 0) && CurrentDBVersion <= new Version(10, 1, 6)) {
                var differenceObjects = new Dictionary<object, string>();
                using (var reader = ExecuteReader("select [Oid], [Model] from [ModelDifferenceObject] where [Model] is not null", false)) {
                    while (reader.Read()) {
                        differenceObjects.Add(reader[0], reader[1] as string);
                    }
                }

                using (var uow = new UnitOfWork(((ObjectSpace)ObjectSpace).Session.DataLayer)) {
                    foreach (var differenceObject in differenceObjects) {
                        var modelDifferenceObject = uow.GetObjectByKey<ModelDifferenceObject>(differenceObject.Key);
                        var serializableDictionary = new SerializableDictionary<string, string>();
                        var xmlReader = XmlReader.Create(new StringReader(differenceObject.Value), new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Auto });
                        serializableDictionary.ReadXml(xmlReader);
                        var aspects = serializableDictionary["aspects"].Split(',').ToList();
                        var defaultAspect = serializableDictionary["DefaultAspect"];
                        defaultAspect = GetDefaultAspectFromVersion9(serializableDictionary, aspects, defaultAspect);

                        if (!string.IsNullOrEmpty(defaultAspect))
                            modelDifferenceObject.AspectObjects.Add(new AspectObject(uow) { Name = CaptionHelper.DefaultLanguage, Xml = defaultAspect });

                        foreach (var aspect in aspects.Where(aspect => !string.IsNullOrEmpty(aspect) && !string.IsNullOrEmpty(serializableDictionary[aspect]))) {
                            modelDifferenceObject.AspectObjects.Add(new AspectObject(uow) { Name = aspect, Xml = serializableDictionary[aspect] });
                        }
                    }

                    uow.CommitChanges();
                }
            }
        }
开发者ID:krazana,项目名称:eXpand,代码行数:32,代码来源:Updater.cs


示例4: AddPatientMedication

 public ActionResult AddPatientMedication(patientmedication medication)
 {
     unitOfWork.Repository<patientmedication>().Insert(medication);
     unitOfWork.Save();
     unitOfWork = new UnitOfWork();
     return PartialView("_PatientMedication", unitOfWork.Repository<patientmedication>().Filter(x => x.PatientId == medication.PatientId).Get());
 }
开发者ID:pavankay,项目名称:blank,代码行数:7,代码来源:PatientController.cs


示例5: GetByProfileID

 public LocationCoreEntity GetByProfileID(string strProfileID)
 {
     LocationCoreEntity objLocationCoreEntity = new LocationCoreEntity();
     try
     {
         Mugurtham.DTO.Profile.Location objLocation = new Mugurtham.DTO.Profile.Location();
         IUnitOfWork objUOW = new UnitOfWork();
         using (objUOW as IDisposable)
             objLocation = objUOW.RepositoryLocation.GetAll().ToList().Where(p => p.ProfileID.Trim().ToLower() == strProfileID.Trim().ToLower()).FirstOrDefault();
         objUOW = null;
         if (objLocation != null)
         {
             using (objLocation as IDisposable)
             {
                 AssignEntityFromDTO(ref objLocation, ref objLocationCoreEntity);
             }
         }
         objLocation = null;
     }
     catch (Exception objEx)
     {
         Helpers.LogExceptionInFlatFile(objEx);
     }
     return objLocationCoreEntity;
 }
开发者ID:AnandJS,项目名称:Mugurtham,代码行数:25,代码来源:LocationCore.cs


示例6: Dispose_Then_throw_exception_on_DbContext_get

        public void Dispose_Then_throw_exception_on_DbContext_get()
        {
            var uow1 = new UnitOfWork(_dbContextFactoryMock.Object);
            uow1.Dispose();

            Assert.Throws<ObjectDisposedException>(() => { var dbContext = uow1.DbContext; });
        }
开发者ID:qstream-inactive,项目名称:ENTech-Store,代码行数:7,代码来源:UnitOfWorkTest.cs


示例7: Create

        //Create template
        public static int Create(TemplateDTO TemplateDTO)
        {
            if (TemplateDTO.Title == null || TemplateDTO.Title == "") { return 0; }

            try
            {
                var Template = new Template();

                GlobalSettings.LoggedInClientId = TemplateDTO.ClientId;
                int PartnerId = ClientService.GetById(TemplateDTO.ClientId).PartnerId;
                GlobalSettings.LoggedInPartnerId = PartnerId;

                UnitOfWork uow = new UnitOfWork();
                Template = Transform.TemplateToDomain(TemplateDTO);
                uow.TemplateRepo.Insert(Template);

                uow.SaveChanges();
                TemplateDTO.Id = Template.Id;
                return TemplateDTO.Id;

            }

            catch (Exception)
            {
                throw;
            }
        }
开发者ID:Prasadambulkar3,项目名称:msgBlaster-api,代码行数:28,代码来源:TemplateService.cs


示例8: DeleteUser

        TestResult DeleteUser()
        {
            using (var unitOfWork = new UnitOfWork(new AuthorizationModuleFactory(false)))
            {
                var UserService = new UserService(unitOfWork);
                var testUser = UserService.Get(user => user.Login == "ivan_test++").FirstOrDefault();
                UserService.Delete(testUser);

                try
                {
                    var result = unitOfWork.Commit();
                    if (result.Count > 0)
                        return new TestResult(TestResultType.Failure, MethodBase.GetCurrentMethod().Name, result.First().ErrorMessage);
                }
                catch (Exception ex)
                {
                    while (ex.InnerException != null)
                        ex = ex.InnerException;
                    return new TestResult(TestResultType.Failure, MethodBase.GetCurrentMethod().Name, ex.Message);
                }

            }

            using (var unitOfWork = new UnitOfWork(new AuthorizationModuleFactory(false)))
            {
                var UserService = new UserService(unitOfWork);
                User testUser = UserService.Get(user => user.Login == "ivan_test++").FirstOrDefault();
                if (testUser != null)
                    return new TestResult(TestResultType.Failure, MethodBase.GetCurrentMethod().Name, "Can find deleted user.");
                else
                    return new TestResult(TestResultType.Success, MethodBase.GetCurrentMethod().Name, "User deleted successfully.");
            }
        }
开发者ID:vano-lukashuk,项目名称:StudentBank,代码行数:33,代码来源:UserTest.cs


示例9: ShouldAllowByDefaultRegisterDataSourcesWithSameName

        public virtual void ShouldAllowByDefaultRegisterDataSourcesWithSameName()
        {
            try
            {
                InternalEnvironment.RegisterDataSource(new DataSource(il => new NullDataSession()));
                InternalEnvironment.RegisterDataSource(new DataSource(il => new NullDataSession()));

                using (var uow = new UnitOfWork())
                {
                    Awaken(uow);
                }

                InternalEnvironment.RegisterDataSource(new DataSource("test", IsolationLevel.RepeatableRead, il => new NullDataSession()));
                InternalEnvironment.RegisterDataSource(new DataSource("test", il => new NullDataSession()));

                using (var uow = new UnitOfWork("test"))
                {
                    Awaken(uow);
                }

                Assert.That(
                    () => InternalEnvironment.RegisterDataSource(new DataSource(il => new NullDataSession()), true), 
                    Throws.Exception.With.Message.EqualTo("Data source with name: '' has already been registered."));

                Assert.That(
                    () => InternalEnvironment.RegisterDataSource(new DataSource("test", il => new NullDataSession()), true), 
                    Throws.Exception.With.Message.EqualTo("Data source with name: 'test' has already been registered."));
            }
            finally
            {
                InternalEnvironment.UnregisterDataSource();
                InternalEnvironment.UnregisterDataSource("test");
            }
        }
开发者ID:NikGovorov,项目名称:Taijutsu,代码行数:34,代码来源:DataSourceFixture.cs


示例10: updateObjectType

 //        private void createObjectTypeColumn(XPClassInfo xpClassInfo, UnitOfWork unitOfWork)
 //        {
 //            unitOfWork.CreateObjectTypeRecords(xpClassInfo);
 //            var newObject = xpClassInfo.CreateNewObject(unitOfWork);
 //            unitOfWork.CommitChanges();
 //            unitOfWork.Delete(newObject);
 //            unitOfWork.CommitChanges();
 //        }
 private void updateObjectType(UnitOfWork unitOfWork, XPClassInfo xpClassInfo, XPClassInfo mergedXPClassInfo, IDbCommand command)
 {
     var propertyName = XPObject.Fields.ObjectType.PropertyName;
     command.CommandText = "UPDATE [" + getTableName(mergedXPClassInfo) + "] SET " + propertyName + "=" + unitOfWork.GetObjectType(xpClassInfo).Oid +
                           " WHERE " + propertyName + " IS NULL OR " + propertyName + "=" +unitOfWork.GetObjectType(mergedXPClassInfo).Oid;
     command.ExecuteNonQuery();
 }
开发者ID:cevious,项目名称:eXpand,代码行数:15,代码来源:XpoObjectMerger.cs


示例11: FrmCrearTipoNomina

 public FrmCrearTipoNomina(TipoNomina tiponomina, XPCollection xpcTipoNomina, UnitOfWork uow)
     : this()
 {
     this.TipoNomina = tiponomina;
     this.uow = uow;
     this.xpcTipoNomina = xpcTipoNomina;
 }
开发者ID:jmurataya,项目名称:Nomina,代码行数:7,代码来源:FrmCrearTipoNomina.cs


示例12: RefreshUsersList

 private void RefreshUsersList()
 {
     repository = UnitOfWork.CreateInstance();
     AllUsers = repository.Users.GetAll().OrderBy(u=>u.UserName).ToList();
     UserListViewModel viewModel = new UserListViewModel(AllUsers);
     usersbindingSource.DataSource = viewModel.Users;
 }
开发者ID:USAID-DELIVER-PROJECT,项目名称:ethiopia-hcmis-warehouse,代码行数:7,代码来源:UsersListView.cs


示例13: Setup

        public override void Setup(ApplicationModulesManager moduleManager) {
            base.Setup(moduleManager);
            var businessClassesList = GetAdditionalClasses(moduleManager);
            WCTypesInfo.Instance.Register(businessClassesList);
            if (Application == null || GetPath() == null)
                return;
            Application.SettingUp += ApplicationOnSettingUp;
            if (FullConnectionString != null) {
                var xpoMultiDataStoreProxy = new SqlMultiDataStoreProxy(FullConnectionString, GetReflectionDictionary());
                using (var dataLayer = new SimpleDataLayer(xpoMultiDataStoreProxy)) {
                    using (var session = new Session(dataLayer)) {
                        using (var unitOfWork = new UnitOfWork(session.DataLayer)) {
                            RunUpdaters(session);
                            AddDynamicModules(moduleManager, unitOfWork);
                        }
                    }
                }
            } else {
                var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(assembly => assembly.ManifestModule.ScopeName.EndsWith(CompileEngine.XpandExtension));
                foreach (var assembly1 in assemblies) {
                    moduleManager.AddModule(assembly1.GetTypes().Where(type => typeof(ModuleBase).IsAssignableFrom(type)).Single());
                }
            }


            Application.SetupComplete += ApplicationOnSetupComplete;

        }
开发者ID:testexpand,项目名称:eXpand,代码行数:28,代码来源:WorldCreatorModuleBase.cs


示例14: Create

        public virtual ActionResult Create(TerminalModel terminal)
        {
            try
            {
                using (UnitOfWork unitOfWork = new UnitOfWork())
                {
                    TerminalRepository insertionRepository = new TerminalRepository(unitOfWork.DataContext);
                    DBTerminal dbTerminal = new DBTerminal
                                                {
                                                    Id = terminal.Id,
                                                    PhoneNumber = terminal.PhoneNumber,
                                                    IsPublic = terminal.IsPublic,
                                                    RegionId = terminal.RegionId,
                                                    CorrectionFacilityId = terminal.CorrectionFacilityId,
                                                    Description = terminal.Description,
                                                    IsActive = terminal.IsActive
                                                };
                    insertionRepository.InsertObject(dbTerminal);
                    unitOfWork.Commit();

                    // обновляем идентификатор
                    terminal.Id = dbTerminal.Id;
                }

                // сохраняем идентификатор видеотерминала
                this.WriteInformation("Видеотерминал с идентификатором \"{0}\" добавлен.", terminal.Id);

                return RedirectToAction("Create");
            }
            catch
            {
                return View();
            }
        }
开发者ID:irishsiberian,项目名称:FPSVIdeoCall,代码行数:34,代码来源:TerminalController.cs


示例15: Create

        public async Task<ReturnModel<UserModel>> Create (UserModel userModel)
        {
            var result = new ReturnModel<UserModel> { Status = true };
            using(var session = new UnitOfWork<FoodMenuEntities>())
            {
                var userRepository = session.GetRepository<IUserRepository>();

                if(!(await userRepository.ValidateEmail(userModel.Email,userModel.Id)))
                {
                    result.Error = ("כתובת האמייל כבר בשימוש.");
                    result.Status = false;
                    return result;
                }

                var user = new User();
                user.Id = userModel.Id;
                user.Email = userModel.Email;
                user.Password = userModel.Password;
                user.FirstName = userModel.FirstName;
                user.LastName = userModel.LastName;
                user.BusinessId = userModel.BusinessId;
                user.Address = userModel.Address;
                user.IsActive = true;
                userRepository.Add(user);

                await session.SaveChangesAsync();

                userModel.Id = user.Id;
                userModel.Token = Guid.NewGuid().ToString();
                result.Result = userModel;
                return result;
            }
        }
开发者ID:mberaz,项目名称:foodMenu,代码行数:33,代码来源:UsersBL.cs


示例16: Integration_LogDataContext_URF_QueryFluent_CallInfo_Include_StationCallsign_Return_StationCallsign

        public void Integration_LogDataContext_URF_QueryFluent_CallInfo_Include_StationCallsign_Return_StationCallsign()
        {
            List<CallInfo> callis = null;

            using (IDataContextAsync context = new ContestqsoDataContext())
            using (IUnitOfWorkAsync unitOfWorkData = new UnitOfWork(context))
            {
                bool caught = false;
                IRepositoryAsync<CallInfo> _CallinfoRepository = new Repository<CallInfo>(context, unitOfWorkData);

                try
                {
                    TestContext.WriteLine("Integration_LogDataContext_URF_QueryFluent_CallInfo_Include_StationCallsign_Return_StationCallsign");
                    //tracked
                    callis = _CallinfoRepository.Query(x => x.UserName == "default")
                        .Include(x => x.Station).Include(x => x.CallSign)
                        .Select().OrderBy(t => t.SessionName).ThenBy(t => t.CallGroup)
                        .ToList();

                }
                catch (Exception ex)
                {
                    TestContext.WriteLine(string.Format("Integration_LogDataContext_URF_QueryFluent_CallInfo_Include_StationCallsign_Return_StationCallsign exception {0}", ex.Message));
                    caught = true;
                }
                Assert.IsFalse(caught);  //exception
                Assert.IsNotNull(callis);
                Assert.IsInstanceOfType(callis, typeof(List<CallInfo> ) );
                Assert.AreEqual(3, callis.Count );
                Assert.IsNotNull(callis[0].CallSign);
                Assert.IsNotNull(callis[0].Station);

            }
        }
开发者ID:psws,项目名称:logqso.mvc,代码行数:34,代码来源:IntegrationURFQuertable.cs


示例17: GetAll

        public Task<FormatedList<UserModel>> GetAll (NameValueCollection requestParams)
        {
            return Task.Run(() =>
            {
                using(var session = new UnitOfWork<FoodMenuEntities>())
                {
                    IUserRepository userRepository = session.GetRepository<IUserRepository>();

                    var userList = userRepository.Find(u => u.IsActive).Select(u => new UserModel
                    {
                        Id = u.Id,
                        Email = u.Email,
                        Password = u.Password,
                        FirstName = u.FirstName,
                        LastName = u.LastName,
                        BusinessId = u.BusinessId,
                        Address = u.Address,
                    });

                    var parser = new DataTableEntityParser<UserModel>(requestParams,userList.AsQueryable());

                    return parser.Parse();
                }
            });
        }
开发者ID:mberaz,项目名称:foodMenu,代码行数:25,代码来源:UsersBL.cs


示例18: Integration_LogDataContext_URF_QueryableTrack_IncludeParam_Station_Return_Station_Track

        public void Integration_LogDataContext_URF_QueryableTrack_IncludeParam_Station_Return_Station_Track()
        {
            List<CallInfo> callis = null;
            IQueryable<CallInfo> CallInfo1 = null;

            using (IDataContextAsync context = new ContestqsoDataContext())
            using (IUnitOfWorkAsync unitOfWork = new UnitOfWork(context))
            {
                bool caught = false;
                IRepositoryAsync<CallInfo> _CallinfoRepository = new Repository<CallInfo>(context, unitOfWork);
                try
                {
                    //var LogQ = _logRepository.Queryable(x => x.LogId == 1, x => x.Stations, x => x.CallSign);
                    //CallInfo1 = _CallinfoRepository.Item(x => x.UserName == "default", x => x.Station);
                    CallInfo1 = _CallinfoRepository.QueryableTrack(false, x => x.UserName == "default", x => x.Station);
                    callis = CallInfo1.ToList();
                }
                catch (Exception ex)
                {
                    TestContext.WriteLine(string.Format("Integration_LogDataContext_URF_QueryableTrack_IncludeParam_Station_Return_Station_Track exception {0}", ex.Message));
                    caught = true;
                }
                Assert.IsFalse(caught);  //exception
                Assert.IsNotNull(CallInfo1);
                Assert.IsInstanceOfType(CallInfo1, typeof(IQueryable<CallInfo>));
                Assert.AreEqual(3, callis.Count );
                //check if tracked
                //Assert.AreEqual(CallInfo1.Where(z=>z.CallGroup == (int)CallGroupEnum.CALL1).Select(x=>x.CallsignId).SingleOrDefault().))
                Assert.AreEqual(Infrastructure.ObjectState.Unchanged, callis[0].ObjectState);
                Assert.IsNull(callis[0].CallSign);
                Assert.IsNotNull(callis[0].Station);
               Assert.IsTrue(_CallinfoRepository.GetEntityTrackingState(callis[0]));  
            }
        }
开发者ID:psws,项目名称:logqso.mvc,代码行数:34,代码来源:IntegrationURFQuertable.cs


示例19: CreateObjectSpaceCore

 protected override IObjectSpace CreateObjectSpaceCore(UnitOfWork unitOfWork, ITypesInfo typesInfo) {
     var objectSpace = new XpandObjectSpace(new XpandUnitOfWork(unitOfWork.DataLayer), typesInfo) {
         AsyncServerModeSourceResolveSession = AsyncServerModeSourceResolveSession,
         AsyncServerModeSourceDismissSession = AsyncServerModeSourceDismissSession
     };
     return objectSpace;
 }
开发者ID:krazana,项目名称:eXpand,代码行数:7,代码来源:XpandObjectSpaceProvider.cs


示例20: DailyUrgentPoReport

 public DailyUrgentPoReport()
 {
     uow = new UnitOfWork();
     _ReportName = @"DailyUrgentPoReport.xls";
     _SheetName = @"主页";
     _SaveFilePath = string.Format(@"{0}DailyUrgentPoReport - NPD\DailyUrgentPoReport_{1}.xls", SystemSetting.GetInstance(uow).WIPReportPath, DateTime.Today.ToString("yyyy_MM_dd"));
 }
开发者ID:kamchung322,项目名称:Namwah,代码行数:7,代码来源:DailyUrgentPoReport.cs



注:本文中的UnitOfWork类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# UnitOfWorkScope类代码示例发布时间:2022-05-24
下一篇:
C# Unit类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap