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


C# DiscoDataContext.SaveChanges方法代码示例

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


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

示例1: CreateUserFlag

        public static UserFlag CreateUserFlag(DiscoDataContext Database, UserFlag UserFlag)
        {
            // Verify
            if (string.IsNullOrWhiteSpace(UserFlag.Name))
                throw new ArgumentException("The User Flag Name is required");

            // Name Unique
            if (_cache.GetUserFlags().Any(f => f.Name == UserFlag.Name))
                throw new ArgumentException("Another User Flag already exists with that name", "UserFlag");

            // Clone to break reference
            var flag = new UserFlag()
            {
                Name = UserFlag.Name,
                Description = UserFlag.Description,
                Icon = UserFlag.Icon,
                IconColour = UserFlag.IconColour,
                UsersLinkedGroup = UserFlag.UsersLinkedGroup,
                UserDevicesLinkedGroup = UserFlag.UserDevicesLinkedGroup
            };

            Database.UserFlags.Add(flag);
            Database.SaveChanges();

            _cache.AddOrUpdate(flag);

            return flag;
        }
开发者ID:garysharp,项目名称:Disco,代码行数:28,代码来源:UserFlagService.cs

示例2: ExecuteTask

        protected override void ExecuteTask()
        {
            var forestServers = DiscoverForestServers();
            ADDiscoverForestServers.ForestServers = forestServers;

            // Restrict Searching Entire Forest if to many servers
            using (DiscoDataContext Database = new DiscoDataContext())
            {
                var searchEntireForest = Database.DiscoConfiguration.ActiveDirectory.SearchAllForestServers;

                // Check explicitly configured: No
                if (!searchEntireForest.HasValue || searchEntireForest.Value)
                {
                    // Not Configured, or explicitly configured: Yes
                    if (forestServers.Count > ActiveDirectory.MaxForestServerSearch)
                    {
                        // Update Database
                        Database.DiscoConfiguration.ActiveDirectory.SearchAllForestServers = false;
                    }
                    else
                    {
                        // Default
                        Database.DiscoConfiguration.ActiveDirectory.SearchAllForestServers = true;
                    }

                    Database.SaveChanges();
                }
            }
        }
开发者ID:garysharp,项目名称:Disco,代码行数:29,代码来源:ADDiscoverForestServers.cs

示例3: Apply

        public bool Apply(DiscoDataContext Database)
        {
            if (RecordAction == EntityState.Detached || !HasError)
            {
                Device device;

                if (RecordAction == EntityState.Unchanged)
                {
                    // Unchanged - No Action Required
                    return false;
                }
                else if (RecordAction == EntityState.Modified)
                {
                    device = Database.Devices.Find(this.DeviceSerialNumber);
                }
                else if (RecordAction == EntityState.Added)
                {
                    // Use 'Add Device Offline' default if available
                    var deviceProfileId = Database.DiscoConfiguration.DeviceProfiles.DefaultAddDeviceOfflineDeviceProfileId;
                    if (deviceProfileId == 0)
                    {
                        deviceProfileId = Database.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId;
                    }

                    // Create Device
                    device = new Device()
                    {
                        SerialNumber = DeviceSerialNumber.ToUpper(),
                        CreatedDate = DateTime.Now,
                        AllowUnauthenticatedEnrol = true,
                        DeviceProfileId = deviceProfileId,
                        DeviceModelId = 1 // Default 'Unknown Device Model'
                    };
                    Database.Devices.Add(device);
                }
                else
                {
                    // Invalid State
                    return false;
                }

                bool changesMade = (RecordAction == EntityState.Added);

                foreach (var field in Fields.Cast<DeviceImportFieldBase>())
                {
                    changesMade = field.Apply(Database, device) || changesMade;
                }

                // Commit Changes
                if (changesMade)
                    Database.SaveChanges();

                return changesMade;
            }

            // Record has Errors
            return false;
        }
开发者ID:garysharp,项目名称:Disco,代码行数:58,代码来源:DeviceImportRecord.cs

示例4: BuildResponse

        public static MacEnrolResponse BuildResponse(this MacEnrol request)
        {
            if (HttpContext.Current == null)
                throw new PlatformNotSupportedException("This function can only be accessed from within ASP.NET");

            using (DiscoDataContext database = new DiscoDataContext())
            {
                MacEnrolResponse response = DeviceEnrolment.MacEnrol(database, request, false);
                database.SaveChanges();
                return response;
            }
        }
开发者ID:garysharp,项目名称:Disco,代码行数:12,代码来源:ClientServicesExtensions.cs

示例5: MigrateDatabase

 internal static void MigrateDatabase(DiscoDataContext Database)
 {
     // Migrate all organisation addresses to JSON
     if (Database.ConfigurationItems.Count(i => i.Scope == scope && !i.Value.StartsWith("{")) > 0)
     {
         var items = Database.ConfigurationItems.Where(i => i.Scope == scope && !i.Value.StartsWith("{")).ToList();
         items.ForEach(i =>
         {
             i.Value = JsonConvert.SerializeObject(OrganisationAddress.FromConfigurationEntry(int.Parse(i.Key), i.Value));
         });
         Database.SaveChanges();
     }
 }
开发者ID:garysharp,项目名称:Disco,代码行数:13,代码来源:OrganisationAddressesConfiguration.cs

示例6: OnRemoveUnsafe

        public static void OnRemoveUnsafe(this UserFlagAssignment fa, DiscoDataContext Database, User RemovingUser)
        {
            fa.RemovedDate = DateTime.Now;
            fa.RemovedUserId = RemovingUser.UserId;

            if (!string.IsNullOrWhiteSpace(fa.UserFlag.OnUnassignmentExpression))
            {
                try
                {
                    Database.SaveChanges();
                    var expressionResult = fa.EvaluateOnUnassignmentExpression(Database, RemovingUser, fa.AddedDate);
                    if (!string.IsNullOrWhiteSpace(expressionResult))
                    {
                        fa.OnUnassignmentExpressionResult = expressionResult;
                        Database.SaveChanges();
                    }
                }
                catch (Exception ex)
                {
                    SystemLog.LogException("User Flag Expression - OnUnassignmentExpression", ex);
                }
            }
        }
开发者ID:garysharp,项目名称:Disco,代码行数:23,代码来源:UserFlagExtensions.cs

示例7: ExecuteTask

        protected override void ExecuteTask()
        {
            int changeCount;

            this.Status.UpdateStatus(1, "Starting", "Connecting to the Database and initializing the environment");
            using (DiscoDataContext database = new DiscoDataContext())
            {
                UpdateLastNetworkLogonDates(database, this.Status);
                Status.UpdateStatus(95, "Updating Database", "Writing last network logon dates to the Database");
                changeCount = database.SaveChanges();
                Status.Finished(string.Format("{0} Device last network logon dates updated", changeCount), "/Config/SystemConfig");
            }

            Status.LogInformation($"Updated LastNetworkLogon Device Property for Device/s, {changeCount:N0} changes");
        }
开发者ID:garysharp,项目名称:Disco,代码行数:15,代码来源:ADNetworkLogonDatesUpdateTask.cs

示例8: SeedDatabase

 public static void SeedDatabase()
 {
     // Seed/Update Database
     using (DiscoDataContext database = new DiscoDataContext())
     {
         database.SeedDatabase();
         try
         {
             database.SaveChanges();
         }
         catch (Exception ex)
         {
             System.Diagnostics.Debug.WriteLine(ex.Message);
             throw;
         }
     }
 }
开发者ID:garysharp,项目名称:Disco,代码行数:17,代码来源:DiscoDataMigrator.cs

示例9: CreateJobQueue

        public static JobQueueToken CreateJobQueue(DiscoDataContext Database, JobQueue JobQueue)
        {
            // Verify
            if (string.IsNullOrWhiteSpace(JobQueue.Name))
                throw new ArgumentException("The Job Queue Name is required");

            // Name Unique
            if (_cache.GetQueues().Any(q => q.JobQueue.Name == JobQueue.Name))
                throw new ArgumentException("Another Job Queue already exists with that name", "JobQueue");

            // Sanitize Subject Ids
            if (string.IsNullOrWhiteSpace(JobQueue.SubjectIds))
            {
                JobQueue.SubjectIds = null;
            }
            else
            {
                var subjectIds = JobQueue.SubjectIds.Split(',');
                foreach (var subjectId in subjectIds)
                {
                    UserService.GetUser(subjectId, Database);
                }
                JobQueue.SubjectIds = string.Join(",", Database.Users.Where(u => subjectIds.Contains(u.UserId)).Select(u => u.UserId));
            }

            // Clone to break reference
            var queue = new JobQueue()
            {
                Name = JobQueue.Name,
                Description = JobQueue.Description,
                Icon = JobQueue.Icon,
                IconColour = JobQueue.IconColour,
                DefaultSLAExpiry = JobQueue.DefaultSLAExpiry,
                Priority = JobQueue.Priority,
                SubjectIds = JobQueue.SubjectIds
            };

            Database.JobQueues.Add(queue);
            Database.SaveChanges();

            return _cache.UpdateQueue(queue);
        }
开发者ID:garysharp,项目名称:Disco,代码行数:42,代码来源:JobQueueService.cs

示例10: OnAddUserFlagUnsafe

        public static UserFlagAssignment OnAddUserFlagUnsafe(this User u, DiscoDataContext Database, UserFlag flag, User AddingUser, string Comments)
        {
            var fa = new UserFlagAssignment()
            {
                UserFlag = flag,
                User = u,
                AddedDate = DateTime.Now,
                AddedUser = AddingUser,
                Comments = string.IsNullOrWhiteSpace(Comments) ? null : Comments.Trim()
            };

            Database.UserFlagAssignments.Add(fa);

            if (!string.IsNullOrWhiteSpace(flag.OnAssignmentExpression))
            {
                try
                {
                    Database.SaveChanges();
                    var expressionResult = fa.EvaluateOnAssignmentExpression(Database, AddingUser, fa.AddedDate);
                    if (!string.IsNullOrWhiteSpace(expressionResult))
                    {
                        fa.OnAssignmentExpressionResult = expressionResult;
                        Database.SaveChanges();
                    }
                }
                catch (Exception ex)
                {
                    SystemLog.LogException("User Flag Expression - OnAssignmentExpression", ex);
                }
            }

            return fa;
        }
开发者ID:garysharp,项目名称:Disco,代码行数:33,代码来源:UserFlagExtensions.cs

示例11: DeleteAuthorizationRole

        public static void DeleteAuthorizationRole(DiscoDataContext Database, AuthorizationRole Role)
        {
            if (Role == null)
                throw new ArgumentNullException("Role");

            Database.AuthorizationRoles.Remove(Role);
            Database.SaveChanges();

            AuthorizationLog.LogRoleDeleted(Role, CurrentUserId);

            // Remove from Role Cache
            RoleCache.RemoveRole(Role);

            // Flush User Cache
            Cache.FlushCache();
        }
开发者ID:garysharp,项目名称:Disco,代码行数:16,代码来源:UserService.cs

示例12: CreateAuthorizationRole

        public static int CreateAuthorizationRole(DiscoDataContext Database, AuthorizationRole Role)
        {
            if (Role == null)
                throw new ArgumentNullException("Role");

            if (string.IsNullOrWhiteSpace(Role.ClaimsJson))
                Role.ClaimsJson = JsonConvert.SerializeObject(new RoleClaims());

            Database.AuthorizationRoles.Add(Role);
            Database.SaveChanges();

            AuthorizationLog.LogRoleCreated(Role, CurrentUserId);

            // Add to Cache
            RoleCache.AddRole(Role);

            // Flush User Cache
            Cache.FlushCache();

            return Role.Id;
        }
开发者ID:garysharp,项目名称:Disco,代码行数:21,代码来源:UserService.cs

示例13: Database

        public virtual ActionResult Database(DatabaseModel model)
        {
            if (ModelState.IsValid)
            {
                // Continue with Configuration
                var connectionString = model.ToConnectionString();

                // Try Creating/Migrating
                connectionString.ConnectTimeout = 5;
                Disco.Data.Repository.DiscoDatabaseConnectionFactory.SetDiscoDataContextConnectionString(connectionString.ToString(), false);

                try
                {
                    Disco.Data.Migrations.DiscoDataMigrator.MigrateLatest(true);
                }
                catch (Exception ex)
                {
                    // Find inner exception
                    SqlException sqlException = null;
                    Exception innermostException = ex;
                    do
                    {
                        if (sqlException == null)
                            sqlException = innermostException as SqlException;
                        if (innermostException.InnerException != null)
                            innermostException = innermostException.InnerException;
                        else
                            break;
                    } while (true);

                    if (sqlException != null)
                    {
                        ModelState.AddModelError(string.Empty, string.Format("Unable to create or migrate the database to the latest version: [{0}] {1}", sqlException.GetType().Name, sqlException.Message));
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, string.Format("Unable to create or migrate the database to the latest version: [{0}] {1}", innermostException.GetType().Name, innermostException.Message));
                    }
                }

                if (ModelState.IsValid)
                {
                    // Save Connection String
                    //Disco.Data.Repository.DiscoDatabaseConnectionFactory.SetDiscoDataContextConnectionString(model.ToConnectionString().ToString(), true);
                    // Write Organisation Name into DB
                    using (DiscoDataContext database = new DiscoDataContext())
                    {
                        database.DiscoConfiguration.OrganisationName = DiscoApplication.OrganisationName;
                        database.SaveChanges();
                    }

                    return RedirectToAction(MVC.InitialConfig.FileStore());
                }
            }

            return View(model);
        }
开发者ID:garysharp,项目名称:Disco,代码行数:57,代码来源:InitialConfigController.cs

示例14: FileStore

        public virtual ActionResult FileStore(FileStoreModel m)
        {
            if (ModelState.IsValid)
            {
                using (DiscoDataContext database = new DiscoDataContext())
                {
                    database.DiscoConfiguration.DataStoreLocation = m.FileStoreLocation;
                    database.SaveChanges();

                    // Extract DataStore Template into FileStore
                    var templatePath = Server.MapPath("~/ClientBin/DataStoreTemplate.zip");
                    if (System.IO.File.Exists(templatePath))
                    {
                        try
                        {
                            using (ZipArchive templateArchive = ZipFile.Open(templatePath, ZipArchiveMode.Read))
                            {
                                foreach (var entry in templateArchive.Entries)
                                {
                                    var entryDestinationPath = Path.Combine(m.FileStoreLocation, entry.FullName);
                                    if (System.IO.File.Exists(entryDestinationPath))
                                        System.IO.File.Delete(entryDestinationPath);
                                }
                                templateArchive.ExtractToDirectory(m.FileStoreLocation);
                            }
                        }
                        catch (Exception ex)
                        {
                            ModelState.AddModelError(string.Empty, string.Format("Unable to extract File Store template: [{0}] {1}", ex.GetType().Name, ex.Message));
                        }
                    }

                    // Initialize Core Environment
                    AppConfig.InitalizeCoreEnvironment(database);
                }

                return RedirectToAction(MVC.InitialConfig.Administrators());
            }

            m.ExpandDirectoryModel();

            return View(m);
        }
开发者ID:garysharp,项目名称:Disco,代码行数:43,代码来源:InitialConfigController.cs

示例15: MigrateAuthorizationRoles

        /// <summary>
        /// Migrates authorization role claims to conform with changes to Disco since the last release.
        /// Claims are only added when the meaning of an existing claim has changed (or expanded/contracted) to improve the migration experience.
        /// </summary>
        private static void MigrateAuthorizationRoles(DiscoDataContext Database)
        {
            // Determine roles which need migration from DBv11 -> DBv14
            var affectedRoles_DBv14 = Database.AuthorizationRoles.Where(r => !r.ClaimsJson.Contains("MyJobs")).ToList();
            
            // Determine roles which need migration from DBv14 -> DBv15
            var affectedRoles_DBv15 = Database.AuthorizationRoles.Where(r => !r.ClaimsJson.Contains("RepairProviderDetails")).ToList();

            if (affectedRoles_DBv14.Count > 0)
            {
                foreach (var role in affectedRoles_DBv14)
                {
                    var claims = JsonConvert.DeserializeObject<RoleClaims>(role.ClaimsJson);

                    // MyJobs replaces 'AwaitingTechnicianAction' jobs on the Job page.
                    if (claims.Job.Lists.AwaitingTechnicianAction)
                    {
                        claims.Job.Lists.MyJobs = true;
                        claims.Job.Lists.MyJobsOrphaned = true;
                    }
                    // Stale Jobs expands on Long Running Jobs (and replaces it on the Job page)
                    if (claims.Job.Lists.LongRunningJobs)
                    {
                        claims.Job.Lists.StaleJobs = true;
                    }
                    // Greater control to create jobs was added, this adds claims to keep the behaviour the same for existing roles
                    if (claims.Job.Actions.Create)
                    {
                        claims.Job.Types.CreateHMisc = true;
                        claims.Job.Types.CreateHNWar = true;
                        claims.Job.Types.CreateHWar = true;
                        claims.Job.Types.CreateSApp = true;
                        claims.Job.Types.CreateSOS = true;
                        claims.Job.Types.CreateSImg = true;
                        claims.Job.Types.CreateUMgmt = true;
                    }
                    // A claim was added to control whether Current User Assignments could be shown (independently of User Assignment History)
                    if (claims.User.ShowAssignmentHistory)
                    {
                        claims.User.ShowAssignments = true;
                    }
                    // A claim was added to control whether User personal details could be shown
                    if (claims.User.Show)
                    {
                        claims.User.ShowDetails = true;
                    }

                    role.ClaimsJson = Newtonsoft.Json.JsonConvert.SerializeObject(claims);
                }

                Database.SaveChanges();
            }

            if (affectedRoles_DBv15.Count > 0)
            {
                foreach (var role in affectedRoles_DBv15)
                {
                    var claims = JsonConvert.DeserializeObject<RoleClaims>(role.ClaimsJson);

                    // If the user previously had the ability to view warranty provider details, they probably should be able to view repair provider details (new feature).
                    if (claims.Job.Properties.WarrantyProperties.ProviderDetails)
                    {
                        claims.Job.Properties.NonWarrantyProperties.RepairProviderDetails = true;
                    }

                    role.ClaimsJson = Newtonsoft.Json.JsonConvert.SerializeObject(claims);
                }

                Database.SaveChanges();
            }
        }
开发者ID:garysharp,项目名称:Disco,代码行数:75,代码来源:RoleCache.cs


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