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


C# DbContext.SaveChanges方法代码示例

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


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

示例1: Main

        private static void Main(string[] args)
        {
            var totalElementos = _objetivos.Sum(a => a.Monto);

            foreach (var item in _objetivos)
            {
                item.Porcentaje =
                    Math.Round(
                        item.Monto/(totalElementos > 0 ? totalElementos : item.Monto), 4);
            }

            var p = new DbContext();
            p.Objetivos.RemoveRange(p.Objetivos.ToList());
            p.SaveChanges();
            if (!p.Objetivos.Any())
            {
                p.Objetivos.AddRange(_objetivos);
                p.SaveChanges();
            }
            Console.WriteLine("From Memory");
            Console.WriteLine("Total Elementos {0}", totalElementos);
            Console.WriteLine("Total Porcentaje {0}", _objetivos.Sum(a => a.Porcentaje));

            Console.WriteLine("From Db");
            Console.WriteLine("Total Elementos {0}", p.Objetivos.Sum(a => a.Monto));
            Console.WriteLine("Total Porcentaje {0}", p.Objetivos.Sum(a => a.Porcentaje));
            Console.WriteLine("Total Porcentaje {0}", DoubleConverter.ToExactString((Double)p.Objetivos.Sum(a => a.Porcentaje)));

            Console.ReadKey();
        }
开发者ID:Joanstan,项目名称:DistObje,代码行数:30,代码来源:Program.cs

示例2: addPatients

        static void addPatients(DbContext db)
        {
            var patient = new Patient () {
                FirstName = "Bubba", LastName = "Ho-Tep", Age = 1234, PersonalNumber = "1111111231234"
            };
            db.Patients.Add (patient);
            db.SaveChanges ();

            var incident = new Incident()
            {
                InjuryDate = "2010-03-04",
                InjuryHour = 9,
                PersonalNumber = patient.PersonalNumber
            };
            db.Incidents.Add(incident);

            var frac1 = new Fracture()
            {
                AOCode = "33C2",
                IncidentID = incident.ID
            };
            db.Fractures.Add(frac1);

            var frac2 = new Fracture()
            {
                AOCode = "22B1",
                IncidentID = incident.ID
            };
            db.Fractures.Add(frac2);

            var consultation = new Consultation();
            db.Consultations.Add(consultation);

            var procedure = new Procedure() {
                // ConsultationID = consultation.ID,
                FractureID = frac1.ID
            };
            db.Procedures.Add(procedure);

            procedure = new Procedure()
            {
                // ConsultationID = consultation.ID,
                FractureID = frac2.ID
            };
            db.Procedures.Add(procedure);

            //patient = new Patient () {
            //    FirstName = "Joe", LastName = "Schmoe", Age = 35
            //};
            //db.Patients.Add (patient);
            //db.SaveChanges ();

            //injury = new Injury () {
            //    AOCode = "31B2",
            //    InjuryDate = new DateTime (2002, 8, 5),
            //    InjuryHour = 23,
            //    PatientID=patient.ID
            //};
            //db.Injuries.Add (injury);
        }
开发者ID:abingham,项目名称:OhSnap,代码行数:60,代码来源:DbTool.cs

示例3: Cleanup

        public virtual void Cleanup(DbContext context)
        {
            context.Set<BuiltInNonNullableDataTypes>().RemoveRange(context.Set<BuiltInNonNullableDataTypes>());
            context.Set<BuiltInNullableDataTypes>().RemoveRange(context.Set<BuiltInNullableDataTypes>());

            context.SaveChanges();
        }
开发者ID:aishaloshik,项目名称:EntityFramework,代码行数:7,代码来源:BuiltInDataTypesFixtureBase.cs

示例4: Hacer

 public static MensajeDto Hacer(DbContext context, MensajeDto mensajeDto)
 {
     try {
         context.SaveChanges();
     } catch (DbUpdateException e) {
         var mensaje = MensajeAux(e);
         mensajeDto = new MensajeDto() {
             Error = true,
             MensajeDelProceso = mensaje
         };
     } catch (DbEntityValidationException e) {
         var mensajeEntity = e.EntityValidationErrors.First()
             .ValidationErrors.First().ErrorMessage;
         var mensaje = MensajeAux(e);
         mensajeDto = new MensajeDto() {
             Error = true,
             MensajeDelProceso = mensaje + " " + mensajeEntity
         };
     } catch (Exception e) {
         var mensaje = MensajeAux(e);
         mensajeDto = new MensajeDto() {
             Error = true,
             MensajeDelProceso = mensaje
         };
     }
     return mensajeDto;
 }
开发者ID:Nestornjrz,项目名称:Archivos,代码行数:27,代码来源:AgregarModificar.cs

示例5: ProductsModule

        public ProductsModule(DbContext dbContext)
        {
            Handle<AddProductModel, int>(command =>
            {
                var product = dbContext.Set<ProductModel>().Add(new ProductModel()
                {
                    //ProductModelID = 123,
                    Name = "New Product Name - " + DateTime.Now.Ticks,
                    rowguid = Guid.NewGuid(),
                    ModifiedDate = DateTime.UtcNow,
                });
                dbContext.SaveChanges(); // to get the new ProductModelId
                return product.ProductModelID;
            });

            Handle<SetProductModelName>(command =>
            {
                var product = dbContext.Set<ProductModel>().Find(1);
                product.Name = "Classic Vest " + DateTime.UtcNow;
            });

            Handle<AddProductReview>(command =>
            {
                var productReview = new ProductReview(command);
                dbContext.Set<ProductReview>().Add(productReview);
            });
        }
开发者ID:jdaigle,项目名称:CQRSPipelineDemo,代码行数:27,代码来源:ProductsModule.cs

示例6: AddTestData

        protected static void AddTestData(DbContext context)
        {
            var address1 = new Address { Street = "3 Dragons Way", City = "Meereen" };
            var address2 = new Address { Street = "42 Castle Black", City = "The Wall" };
            var address3 = new Address { Street = "House of Black and White", City = "Braavos" };

            context.Set<Person>().AddRange(
                new Person { Name = "Daenerys Targaryen", Address = address1 },
                new Person { Name = "John Snow", Address = address2 },
                new Person { Name = "Arya Stark", Address = address3 },
                new Person { Name = "Harry Strickland" });

            context.Set<Address>().AddRange(address1, address2, address3);

            var address21 = new Address2 { Id = "1", Street = "3 Dragons Way", City = "Meereen" };
            var address22 = new Address2 { Id = "2", Street = "42 Castle Black", City = "The Wall" };
            var address23 = new Address2 { Id = "3", Street = "House of Black and White", City = "Braavos" };

            context.Set<Person2>().AddRange(
                new Person2 { Name = "Daenerys Targaryen", Address = address21 },
                new Person2 { Name = "John Snow", Address = address22 },
                new Person2 { Name = "Arya Stark", Address = address23 });

            context.Set<Address2>().AddRange(address21, address22, address23);

            context.SaveChanges();
        }
开发者ID:RickyLin,项目名称:EntityFramework,代码行数:27,代码来源:OneToOneQueryFixtureBase.cs

示例7: Run

        public static void Run(DbContext db)
        {
            if (!db.Set<Profile>().Any())
                db.Add(new Profile
                {
                    Name = "Alexandre Machado",
                    Email = "[email protected]",
                    Login = "cwinet\alexandrelima"
                });
            if (!db.Set<Skill>().Any())
                db.AddRange(
                    new Skill { SkillName = "ASP.NET" },
                    new Skill { SkillName = "Ruby" },
                    new Skill { SkillName = "JavaScript" }
                    );
            if (!db.Set<Mastery>().Any())
                db.AddRange(
                    new Mastery { Code = 10, Name = "Iniciante", Description = "recordação não-situacional, reconhecimento decomposto, decisão analítica, consciência monitorada" },
                    new Mastery { Code = 20, Name = "Competente", Description = "recordação situacional, reconhecimento decomposto, decisão analítica, consciência monitorada" },
                    new Mastery { Code = 30, Name = "Proeficiente", Description = "recordação situacional, reconhecimento holítico, decisão analítica, consciência monitorada" },
                    new Mastery { Code = 40, Name = "Experiente", Description = "recordação situacional, reconhecimento holítico, decisão intuitiva, consciência monitorada" },
                    new Mastery { Code = 50, Name = "Mestre", Description = "recordação situacional, reconhecimento holítico, decisão intuitiva, consciência absorvida" });

            db.SaveChanges();
        }
开发者ID:Alexandre-Machado,项目名称:SkillMap,代码行数:25,代码来源:Seed.cs

示例8: SaveChanges

        /// <summary>
        /// Wrapper for SaveChanges adding the Validation Messages to the generated exception
        /// </summary>
        /// <param name="context">The context.</param>
        public int SaveChanges(DbContext context)
        {
            try
            {
                return context.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                StringBuilder sb = new StringBuilder();

                foreach (var failure in ex.EntityValidationErrors)
                {
                    sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType());
                    foreach (var error in failure.ValidationErrors)
                    {
                        sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
                        sb.AppendLine();
                    }
                }

                throw new DbEntityValidationException(
                    "Entity Validation Failed - errors follow:\n" +
                    sb.ToString(), ex
                ); // Add the original exception as the innerException
            }
        }
开发者ID:fmoliveira,项目名称:tigra-acad,代码行数:30,代码来源:BootstrapBaseController.cs

示例9: AddActiveDirectoryUser

        protected static void AddActiveDirectoryUser(Guid userId, string name, string accountName, bool isDisabled = false,
            IEnumerable<KeyValuePair<string, string>> customProperties = null)
        {
            using (DbContext writeDbContext = new DbContext())
            {
                User user = new User
                {
                    Id = userId,
                    Name = name,
                    IsDisabled = isDisabled,
                };

                Account account = new Account
                {
                    UserId = user.Id,
                    Name = accountName,
                    Type = AccountType.ActiveDirectory
                };

                user.Accounts.Add(account);

                if (customProperties != null)
                {
                    user.CustomProperties.AddRange(customProperties.Select(c => new CustomProperty { Id = Guid.NewGuid(), Name = c.Key, Value = c.Value }));
                }

                writeDbContext.Users.Add(user);
                writeDbContext.SaveChanges();
            }
        }
开发者ID:affecto,项目名称:dotnet-IdentityManagement,代码行数:30,代码来源:DbTests.cs

示例10: Seed

 public void Seed(DbContext dbContext)
 {
     foreach (var task in m_TaskFactory.CreateSiTasks())
       {
     dbContext.Set<Task>()
          .Add(task);
       }
       dbContext.SaveChanges();
 }
开发者ID:htw-bui,项目名称:OrkHub,代码行数:9,代码来源:InitialSeed.cs

示例11: SeedTiposDocumento

        private void SeedTiposDocumento(DbContext context)
        {
            context.Set<TipoDocumento>().AddRange(new[]
            {
                Dni,
                CarneExtranjeria
            });

            context.SaveChanges();
        }
开发者ID:rmoranter,项目名称:UPC-TP3,代码行数:10,代码来源:SeedBase.cs

示例12: SeedCargos

        private void SeedCargos(DbContext context)
        {
            context.Set<Cargo>().AddRange(new[]
            {
                Conductor,
                Gerente
            });

            context.SaveChanges();
        }
开发者ID:rmoranter,项目名称:UPC-TP3,代码行数:10,代码来源:SeedBase.cs

示例13: PopulateData

        private static void PopulateData(DbContext context, DateTime latestAlbumDate)
        {
            var albums = TestAlbumDataProvider.GetAlbums(latestAlbumDate);

            foreach (var album in albums)
            {
                context.Add(album);
            }

            context.SaveChanges();
        }
开发者ID:Estefani1,项目名称:MusicStore,代码行数:11,代码来源:AnnouncementComponentTest.cs

示例14: EndDbContext

        private void EndDbContext(DbContext dbContext)
        {
            if (dbContext != null)
            {
                if (HttpContext.Current != null)
                {
                    if (HttpContext.Current.Error == null)
                    {
                        dbContext.SaveChanges();
                    }
                }
                else
                {
                    dbContext.SaveChanges();
                }

                dbContext.Database.Connection.Close();
                dbContext.Database.Connection.Dispose();
                dbContext.Dispose();
            }
        }
开发者ID:elranu,项目名称:btr-dalc-prototype,代码行数:21,代码来源:EntityFrameworkUnitOfWork.cs

示例15: FindOrMake

 public static Student FindOrMake(this DbSet<Student> students, string membershipNumber, string forename, string surname, DbContext ctx)
 {
     var student = students.FirstOrDefault(s => s.MembershipNumber == membershipNumber);
     if (student == null) {
         student = new Student() {
             MembershipNumber = membershipNumber,
             Forename = forename,
             Surname = surname
         };
         students.Add(student);
         ctx.SaveChanges();
     }
     return (student);
 }
开发者ID:GiveCampUK,项目名称:SceneAndHeard,代码行数:14,代码来源:Program.cs


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