本文整理汇总了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();
}
示例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);
}
示例3: Cleanup
public virtual void Cleanup(DbContext context)
{
context.Set<BuiltInNonNullableDataTypes>().RemoveRange(context.Set<BuiltInNonNullableDataTypes>());
context.Set<BuiltInNullableDataTypes>().RemoveRange(context.Set<BuiltInNullableDataTypes>());
context.SaveChanges();
}
示例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;
}
示例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);
});
}
示例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();
}
示例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();
}
示例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
}
}
示例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();
}
}
示例10: Seed
public void Seed(DbContext dbContext)
{
foreach (var task in m_TaskFactory.CreateSiTasks())
{
dbContext.Set<Task>()
.Add(task);
}
dbContext.SaveChanges();
}
示例11: SeedTiposDocumento
private void SeedTiposDocumento(DbContext context)
{
context.Set<TipoDocumento>().AddRange(new[]
{
Dni,
CarneExtranjeria
});
context.SaveChanges();
}
示例12: SeedCargos
private void SeedCargos(DbContext context)
{
context.Set<Cargo>().AddRange(new[]
{
Conductor,
Gerente
});
context.SaveChanges();
}
示例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();
}
示例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();
}
}
示例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);
}