当前位置: 首页>>代码示例>>C#>>正文


C# IUnitOfWork.Save方法代码示例

本文整理汇总了C#中IUnitOfWork.Save方法的典型用法代码示例。如果您正苦于以下问题:C# IUnitOfWork.Save方法的具体用法?C# IUnitOfWork.Save怎么用?C# IUnitOfWork.Save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在IUnitOfWork的用法示例。


在下文中一共展示了IUnitOfWork.Save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: StartWorkSession

        public APIResult<TimeCard> StartWorkSession(IUnitOfWork uow, DateTime StartDate, string UserCode)
        {
            var emp = uow.UserRepository.GetEagerLoad(e => e.UserCode.Equals(UserCode, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            if (emp == null)
            {
                return new APIResult<TimeCard>(null, false, "no employee with this user code: " + UserCode, null);
            }

            var tc = uow.TimeCardRepository.GetEagerLoad(t =>
            (t.UserID != null) &&
               t.UserID.Equals(emp.UserID, StringComparison.OrdinalIgnoreCase)
               , orderBy: q => q.OrderByDescending(p => p.StartDate)
               ).FirstOrDefault();
            if (tc != null && tc.timeCardEnum.Equals(TimeCardStatusEnum.open))
            {
                return new APIResult<TimeCard>(null, false, "already an opened time card", null);
            }
            tc = new TimeCard();
            tc.UserID = emp.UserID;
            tc.StartDate = StartDate;
            tc.timeCardEnum = TimeCardStatusEnum.open;
            uow.TimeCardRepository.Insert(tc);
            uow.Save();
            return new APIResult<TimeCard>(tc, true, "a new time card is created", null);
        }
开发者ID:gomaltao,项目名称:HRM,代码行数:25,代码来源:TimeCardServices.cs

示例2: EndWorkSession

        public APIResult<TimeCard> EndWorkSession(IUnitOfWork uow, DateTime EndDate, string UserCode)
        {
            var currentUser  = uow.UserRepository.GetEagerLoad(emp => emp.UserCode.Equals(UserCode, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            if( currentUser == null )
            {
                return new APIResult<TimeCard>(null, false, "no user for this time card", null );
            }
            var tc = uow.TimeCardRepository.GetEagerLoad( t =>
            t.UserID.Equals(currentUser.UserID, StringComparison.OrdinalIgnoreCase)
             && t.timeCardEnum.Equals(TimeCardStatusEnum.open)
            , orderBy: q => q.OrderByDescending(p => p.StartDate))
            //, includeProperties: prop => prop.employee)
            .FirstOrDefault();

            if (tc != null)
            {
                tc.EndDate = EndDate;
                tc.timeCardEnum = TimeCardStatusEnum.close;
                uow.Save();
                return new APIResult<TimeCard>(tc, true, "time card closed", null);
            }
            else
            {
                return new APIResult<TimeCard>(null, false, "no time card to close", null);
            }
        }
开发者ID:gomaltao,项目名称:HRM,代码行数:26,代码来源:TimeCardServices.cs

示例3: UpdateSetting

        public void UpdateSetting(IUnitOfWork unitOfWork, bool value)
        {
            this.Value = value;

            unitOfWork.AppSettingRepository.Update(this);
            unitOfWork.Save();
        }
开发者ID:CodeObsessed,项目名称:drumbleapp,代码行数:7,代码来源:AppSetting.cs

示例4: CreateOrLoadStudent

        public static Student CreateOrLoadStudent(StudentModel studentModel, IUnitOfWork unitOfWork)
        {
            Student student = unitOfWork.StudentsRepository.Get(studentModel.ID);
            if (student != null)
            {
                return student;
            }

            Student newStudent = new Student()
                {
                    FirstName = studentModel.FirstName,
                    LastName = studentModel.LastName,
                    Age = studentModel.Age,
                    Grade = studentModel.Grade,
                    School = CreateOrLoadSchool(studentModel.School, unitOfWork)
                };

            foreach (MarkModel mark in studentModel.Marks)
            {
                newStudent.Marks.Add(MarksMapper.ToMarkEntity(mark));
            }

            unitOfWork.StudentsRepository.Add(newStudent);
            unitOfWork.Save();

            return newStudent;
        }
开发者ID:vladislav-karamfilov,项目名称:TelerikAcademy,代码行数:27,代码来源:Extensions.cs

示例5: DeleteTest

        public void DeleteTest()
        {
            _unitOfWork = _container.Resolve<IUnitOfWork>();
            var user = _unitOfWork.UserRepository.FindById(2);
            _unitOfWork.UserRepository.Delete(user);

            _unitOfWork.Save();
        }
开发者ID:abdurrahman,项目名称:walltage,代码行数:8,代码来源:EntityCrudUnitTests.cs

示例6: FinanceControllerTests

        public FinanceControllerTests()
        {
            _unitOfWork = new UnitOfWorkMock();
            _controller = new FinanceController(_unitOfWork);

            _currentUser = new User {UserName = "currentuser"};
            _currentUserProfile = new UserProfile {User = _currentUser};

            _unitOfWork.GetRepository<User>().Insert(_currentUser);
            _unitOfWork.GetRepository<UserProfile>().Insert(_currentUserProfile);
            _unitOfWork.Save();

            _controller.ControllerContext = CreateControllerContext(_currentUser);
        }
开发者ID:MaratFatkullin,项目名称:Delusion,代码行数:14,代码来源:FinanceControllerTests.cs

示例7: InsertCategoryTest

        public void InsertCategoryTest()
        {
            _unitOfWork = _container.Resolve<IUnitOfWork>();

            var categoryList = new List<Category>
            {
                new Category { AddedBy = "abdurrahman", AddedDate = DateTime.Now, Name = "Abstract" },
                new Category { AddedBy = "abdurrahman", AddedDate = DateTime.Now, Name = "Animals" },
                new Category { AddedBy = "abdurrahman", AddedDate = DateTime.Now, Name = "Music" },
                new Category { AddedBy = "abdurrahman", AddedDate = DateTime.Now, Name = "Movie" },
                new Category { AddedBy = "abdurrahman", AddedDate = DateTime.Now, Name = "Nature" },
                new Category { AddedBy = "abdurrahman", AddedDate = DateTime.Now, Name = "People" },
                new Category { AddedBy = "abdurrahman", AddedDate = DateTime.Now, Name = "Science" },
                new Category { AddedBy = "abdurrahman", AddedDate = DateTime.Now, Name = "City" }
            };
            _unitOfWork.CategoryRepository.BulkInsert(categoryList);
            _unitOfWork.Save();
        }
开发者ID:abdurrahman,项目名称:walltage,代码行数:18,代码来源:EntityCrudUnitTests.cs

示例8: CreateOrLoadSchool

        public static School CreateOrLoadSchool(SchoolDetails schoolDetails, IUnitOfWork unitOfWork)
        {
            School school = unitOfWork.SchoolsRepository.Get(schoolDetails.ID);
            if (school != null)
            {
                return school;
            }

            School newSchool = new School()
                {
                    Name = schoolDetails.Name,
                    Location = schoolDetails.Location
                };

            unitOfWork.SchoolsRepository.Add(newSchool);
            unitOfWork.Save();

            return newSchool;
        }
开发者ID:vladislav-karamfilov,项目名称:TelerikAcademy,代码行数:19,代码来源:Extensions.cs

示例9: Dosomething

        private void Dosomething(EnumRepositoryType repoType, bool useSingleTransaction, IUnitOfWork work, bool showMessages)
        {
            int deleteIndex = 0;
            int editIndex = 0;
            int count = 0;
            try
            {
                string data;

                // Get current count
                count = work.PearsonRepository.Get().Count();

                lblStatistics.Text = "Total pearsons returned: " + count.ToString();

                work.PearsonRepository.Create(new Entities.Pearson { FirstName = "Peter", LastName = "Topolšek" });
                work.PearsonRepository.Create(new Entities.Pearson { FirstName = "Peter", LastName = "Topolšek" });

                if (!useSingleTransaction)
                    work.Save();

                deleteIndex = GetDeleteIndex(count);
                editIndex = GetEditIndex(count);

                data = string.Join(",", work.PearsonRepository.Get().Select(p => p.FirstName).ToArray());

                if (showMessages)
                    MessageBox.Show("Before edit: \n" + data);

                Pearson updatePearson = work.PearsonRepository.Get().ToArray()[editIndex];

                updatePearson.FirstName = "Katarina";
                updatePearson.LastName = "Ročnik";

                work.PearsonRepository.Update(updatePearson);

                Pearson deletePearson = work.PearsonRepository.Get().ToArray()[deleteIndex];

                work.PearsonRepository.Delete(deletePearson.Id);

                if (!useSingleTransaction)
                    work.Save();

                data = string.Join(",", work.PearsonRepository.Get().Select(p => p.FirstName).ToArray());
                if (showMessages)
                    MessageBox.Show("After edit: \n" + data);

                if (showMessages)
                    MessageBox.Show("Final result: \n" + data + "\n Število vseh: " + work.PearsonRepository.Get().Count().ToString());

                if (chkRaiseError.Checked)
                    throw new Exception("Error, nothing should be saved or everything, depends of UnitOfWork/Repository combination you pick...");

                work.Save();

            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: \n" + ex.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
        }
开发者ID:petertop,项目名称:UnitOfWorkDemo,代码行数:60,代码来源:frmMain.cs

示例10: FotoUpload

       public void FotoUpload(HttpPostedFileBase fotoUpload, int ProductID)
       {
           if (fotoUpload == null)
           {
               Logger.Instance.Error("fotoUpload был передан как null");
               throw new ArgumentNullException();
           }

           db = NinjectResolver.Instance.GetService<IUnitOfWork>();
           var settingsPath =
               db.KernelSettingsRepository.GetAll().FirstOrDefault(i => i.Code.Contains("SYS_FOTO_PATH"));

           if (settingsPath == null || string.IsNullOrWhiteSpace(settingsPath.Value) ||
               string.IsNullOrEmpty(settingsPath.Value))
           {
               Logger.Instance.Error("SYS_FOTO_PATH not exist in data base");
               throw new ArgumentNullException();
           }

           var settings =
               db.KernelSettingsRepository.GetAll().FirstOrDefault(i => i.Code.Contains("SYS_MAX_FILES_SIZE"));

           if (settings == null || string.IsNullOrWhiteSpace(settings.Value) || string.IsNullOrEmpty(settings.Value))
           {
               Logger.Instance.Error("SYS_MAX_FILES_SIZE not exist in data base");
               throw new ArgumentNullException();
           }

           int maxSize;

           if (!int.TryParse(settings.Value, out maxSize))
           {
               Logger.Instance.Error("Value of parameter SYS_MAX_FILES_SIZE not was been read");
               throw new FormatException();
           }

           

           if (!CheckFotoExtension(fotoUpload.ContentType))
           {
               throw new FormatException();
           }

           if (fotoUpload.ContentLength > 0 && fotoUpload.ContentLength <= maxSize)
           {
               string ext = Path.GetExtension(fotoUpload.FileName);
               int order =
                   (db.ProductFotoRepository.GetAll()
                       .Where(i => i.ProductID == ProductID)
                       .Max(i => i.SortOrder) ?? 1);

               var outObj = db.ProductFotoRepository.InsertReturn(
                   new t_ProductFoto()
                   {
                       Name = string.Format("{0}{1}",Guid.NewGuid().ToString(),ext),
                       RealName = fotoUpload.FileName,
                       ProductID = ProductID,
                       SortOrder = order
                   }
                   );
               db.Save();
               if (outObj != null)
               {
                   var path = Path.Combine(HttpContext.Current.Server.MapPath(settingsPath.Value), outObj.Name);
                   fotoUpload.SaveAs(path);
               }
               else
               {
                   Logger.Instance.Error("UnityFileUploader not was  write object to database");
                   throw new ArgumentNullException();

               }
           }
           else
           {
               throw new NullReferenceException(string.Format("Файл превышает допустимы размер в {0} Мб.",
                   maxSize / 100000));
           }
       }
开发者ID:munk1,项目名称:TGZStore,代码行数:79,代码来源:UnityFileUploader.cs

示例11: AlbumDelete

       public void AlbumDelete(int albumId) {
           try {
               db = NinjectResolver.Instance.GetService<IUnitOfWork>();

               var photoAlbum = db.PhotoAlbumsRepository.GetById(albumId);
               if (photoAlbum == null)
               {
                   throw new NullReferenceException(string.Format("При удаление альбома возникала ошибка, альбома с ID {0} несуществует",albumId));
               }


               var photos = from p in photoAlbum.t_Photos
                   select p.ID;
               foreach (var photoId in photos)
               {
                   try
                   {
                       FotoAlbumDelete(photoId);
                   }
                   catch (Exception ex)
                   {
                       
                       
                   }
               }
               db.PhotoAlbumsRepository.DeleteById(albumId);
               db.Save();
           }
           catch (Exception e) {
               Logger.Instance.Error("Ошибка удаления фотоальбома. " + e.Message);
           }

       }
开发者ID:munk1,项目名称:TGZStore,代码行数:33,代码来源:UnityFileUploader.cs

示例12: FotoAlbumDelete

       public void FotoAlbumDelete(int fotoID) {
           try {
               db = NinjectResolver.Instance.GetService<IUnitOfWork>();

               var settingsPath =
                   db.KernelSettingsRepository.GetAll().FirstOrDefault(i => i.Code.Contains("SYS_FOTO_PATH"));
               if (settingsPath == null || string.IsNullOrWhiteSpace(settingsPath.Value) ||
                   string.IsNullOrEmpty(settingsPath.Value)) {
                   Logger.Instance.Error("SYS_FILES_PATH not exist in data base");
                   throw new ArgumentNullException();
               }

               var fotoName = db.PhotosRepository.GetById(fotoID).Name;

               var path = Path.Combine(HttpContext.Current.Server.MapPath(settingsPath.Value), fotoName);
               if (File.Exists(path)) {
                   File.Delete(path);
               }

               db.PhotosRepository.DeleteById(fotoID);

               db.Save();
           }
           catch (Exception e) {
               Logger.Instance.Error("Ошибка удаления фотографии. " + e.Message);
           }

       }
开发者ID:munk1,项目名称:TGZStore,代码行数:28,代码来源:UnityFileUploader.cs

示例13: FileUpload

       /// <summary>
       /// Загружает файл на сервер. 
       /// </summary>
       /// <param name="fileUpload">Файл</param>
       /// <returns>ID загруженного файла из БД</returns>
       public int FileUpload(HttpPostedFileBase fileUpload)
       {
           if (fileUpload == null)
           {
               Logger.Instance.Error("fileUpload был передан как null");
               throw new ArgumentNullException();
           }
               db = NinjectResolver.Instance.GetService<IUnitOfWork>();
               var settingsPath =
                   db.KernelSettingsRepository.GetAll().FirstOrDefault(i => i.Code.Contains("SYS_FILES_PATH"));
               if (settingsPath == null || string.IsNullOrWhiteSpace(settingsPath.Value) ||
                   string.IsNullOrEmpty(settingsPath.Value))
               {
                   Logger.Instance.Error("SYS_FILES_PATH not exist in data base");
                   throw new ArgumentNullException();
               }

               var settings =
                   db.KernelSettingsRepository.GetAll().FirstOrDefault(i => i.Code.Contains("SYS_MAX_FILES_SIZE"));

               if (settings == null || string.IsNullOrWhiteSpace(settings.Value) || string.IsNullOrEmpty(settings.Value))
               {
                   Logger.Instance.Error("SYS_MAX_FILES_SIZE not exist in data base");
                   throw new ArgumentNullException();
               }

               int maxSize;

               if (!int.TryParse(settings.Value, out maxSize))
               {
                   Logger.Instance.Error("Value of parameter SYS_MAX_FILES_SIZE not was been read");
                   throw new FormatException();
               }

               if (fileUpload.ContentLength > 0 && fileUpload.ContentLength <= maxSize)
               {

                   var outObj = db.FilesRepository.InsertReturn(
                       new t_Files()
                       {
                           Name = Guid.NewGuid().ToString(),
                           RealName = fileUpload.FileName,
                           Path = settingsPath.Value,
                           Size = (fileUpload.ContentLength/1000),
                           Ext = fileUpload.ContentType
                       }
                       );
                   db.Save();
                   if (outObj != null)
                   {

                       var path = Path.Combine(HttpContext.Current.Server.MapPath(settingsPath.Value), outObj.Name);
                       fileUpload.SaveAs(path);
                       return outObj.ID;
                   }
                   else
                   {
                       Logger.Instance.Error("UnityFileUploader not was  write object to database");
                       throw new ArgumentNullException();

                   }
               }
               else
               {
                   throw new NullReferenceException(string.Format("Файл превышает допустимы размер в {0} Мб.",
                       maxSize/100000));
               }
       }
开发者ID:munk1,项目名称:TGZStore,代码行数:73,代码来源:UnityFileUploader.cs

示例14: CreateCrash


//.........这里部分代码省略.........
                AutoReporterID		int				
                Processed			bit	-> renamed to AllowToBeContacted			
                HasDiagnosticsFile	bit	always true		
                HasNewLogFile		bit				
                HasMetaData			bit	always true
            */

	        // Set the unused fields to the default values.
	        //NewCrash.Title = "";			removed from dbml
	        //NewCrash.Selected = false;	removed from dbml
	        //NewCrash.Version = 4;			removed from dbml
	        //NewCrash.AutoReporterID = 0;	removed from dbml
	        //NewCrash.HasNewLogFile = false;removed from dbml

	        //NewCrash.HasDiagnosticsFile = true;
	        //NewCrash.HasMetaData = true;
            newCrash.UserActivityHint = description.UserActivityHint;
            
            BuildPattern(newCrash);

            if(newCrash.CommandLine == null)
                newCrash.CommandLine = "";

            _unitOfWork.Dispose();
            _unitOfWork = new UnitOfWork(new CrashReportEntities());
	        var callStackRepository = _unitOfWork.CallstackRepository;

	        try
	        {
	            var crashRepo = _unitOfWork.CrashRepository;
                //if we don't have any callstack data then insert the crash and return
	            if (string.IsNullOrEmpty(newCrash.Pattern))
	            {
	                crashRepo.Save(newCrash);
                    _unitOfWork.Save();
	                return newCrash;
	            }

                //If this isn't a new pattern then link it to our crash data model
                if (callStackRepository.Any(data => data.Pattern == newCrash.Pattern))
	            {
                    var callstackPattern = callStackRepository.First(data => data.Pattern == newCrash.Pattern);
	                newCrash.PatternId = callstackPattern.id;
	            }
	            else
	            {
	                //if this is a new callstack pattern then insert into data model and create a new bugg.
	                var callstackPattern = new CallStackPattern { Pattern = newCrash.Pattern };
	                callStackRepository.Save(callstackPattern);
                    _unitOfWork.Save();
	                newCrash.PatternId = callstackPattern.id;
	            }

                //Mask out the line number and File path from our error message.
                var errorMessageString = description.ErrorMessage != null ? String.Join("", description.ErrorMessage) : "";

                //Create our masking regular expressions
                var fileRegex = new Regex(@"(\[File:).*?(])");//Match the filename out the file name
                var lineRegex = new Regex(@"(\[Line:).*?(])");//Match the line no.

                /**
                 * Regex to match ints of two characters or longer
                 * First term ((?<=\s)|(-)) : Positive look behind, match if preceeded by whitespace or if first character is '-'
                 * Second term (\d{3,}) match three or more decimal chracters in a row.
                 * Third term (?=(\s|$)) positive look ahead match if followed by whitespace or end of line/file.
                 */
开发者ID:zhaoyizheng0930,项目名称:UnrealEngine,代码行数:67,代码来源:CrashesController.cs

示例15: UpdateTest

        public void UpdateTest()
        {
            _unitOfWork = _container.Resolve<IUnitOfWork>();
            var user = _unitOfWork.UserRepository.FindById(1);

            user.Username = "xJason";
            user.LastActivity = DateTime.Now;
            //user.UserRoleId = 2;

            _unitOfWork.UserRepository.Update(user);
            _unitOfWork.Save();
        }
开发者ID:abdurrahman,项目名称:walltage,代码行数:12,代码来源:EntityCrudUnitTests.cs


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