本文整理汇总了C#中Db.SaveChanges方法的典型用法代码示例。如果您正苦于以下问题:C# Db.SaveChanges方法的具体用法?C# Db.SaveChanges怎么用?C# Db.SaveChanges使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Db
的用法示例。
在下文中一共展示了Db.SaveChanges方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CleanUp
private void CleanUp()
{
using (var db = new Db())
{
db.Database.ExecuteSqlCommand("DELETE FROM Listings");
db.SaveChanges();
}
}
示例2: SaveOrUpdate
public SaveResult<User> SaveOrUpdate(User u)
{
using (var db = new Db())
{
if (u.Id != 0)
{
db.Entry(u).State = EntityState.Modified;
}
else
{
db.Users.Add(u);
}
db.SaveChanges();
return new SaveResult<User>(true, u);
}
}
示例3: Execute
protected void Execute(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
using (var r = new Db())
{
var dinners = r.Dinners.Where(o => o.Meals.Count() > 2 && o.IsDeleted);
foreach (var dinner in dinners)
{
dinner.IsDeleted = false;
}
var meals = r.Meals.Where(o => o.Picture != null && o.IsDeleted && o.Name.Length > 3);
foreach (var meal in meals)
{
meal.IsDeleted = false;
}
var chefs = r.Chefs.Where(o => o.IsDeleted && o.LastName.Length > 3);
foreach (var chef in chefs)
{
chef.IsDeleted = false;
}
var countries = r.Countries.Where(o => o.IsDeleted && o.Name.Length > 3);
foreach (var country in countries)
{
country.IsDeleted = false;
}
r.SaveChanges();
}
}
catch (Exception ex)
{
ex.Log();
}
}
示例4: Execute
protected void Execute(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
using (var r = new Db())
{
var promotions = r.Promotions.Where(o => o.Products.Count() > 2 && o.IsDeleted);
foreach (var promotion in promotions)
{
promotion.IsDeleted = false;
}
var products = r.Products.Where(o => o.Picture != null && o.IsDeleted && o.Name.Length > 3);
foreach (var product in products)
{
product.IsDeleted = false;
}
var branches = r.Branches.Where(o => o.IsDeleted && o.Address.Length > 3);
foreach (var branch in branches)
{
branch.IsDeleted = false;
}
var countries = r.Countries.Where(o => o.IsDeleted && o.Name.Length > 3);
foreach (var country in countries)
{
country.IsDeleted = false;
}
r.SaveChanges();
}
}
catch (Exception ex)
{
ex.Raize();
}
}
示例5: Main
static void Main(string[] args)
{
var db = new Db();
var item = db.Items.FirstOrDefault();
if (item == null)
{
item = new Item { Name = "Item-" + DateTime.Now };
db.Items.Add(item);
}
var childItem = new ChildItem
{
Name = "ChildItem-" + DateTime.Now,
Parent = item
};
db.ChildItems.Add(childItem);
db.SaveChanges();
Console.WriteLine("{0} - {1}", item.Id, item.Name);
var latestItems = db.ChildItems
.Include(ci => ci.Parent)
.Where(ci => ci.Parent.Id == item.Id)
.ToArray();
var chItems = item.ChildItems.ToArray();
foreach (var chIt in latestItems)
{
Console.WriteLine("{0} - {1}", chIt.Name, chIt.Parent.Name);
}
Console.ReadLine();
}
示例6: Index
public ActionResult Index(HttpPostedFileBase file)
{
var email = "";
if (User.Identity.IsAuthenticated)
email = Membership.GetUser().Email;
UserObj u = CustomUserService.loadUser(email);
if (!u.Supplier)
return RedirectToAction("Login", "Account");
// how to parse a csv using LumenWorks CSV parser, Ref Arian Skehill, Lecturer NCI
IDataparser csv = new CSVParser();
StreamReader reader = new StreamReader(file.InputStream);
csv.setStreamSource(reader);
List<Car> results = csv.parseCars();
var dal = new Db();
var cars = dal.Cars.ToList();
List<string> car_ids = new List<string>();
foreach (var c in cars)
car_ids.Add(c.car_reg);
foreach (var c in results)
{
if (car_ids.Contains(c.car_reg))
continue;
c.SupplierId = u.Id();
dal.Cars.Add(c);
}
dal.SaveChanges();
return RedirectToAction("Index");
}
示例7: Main
static void Main(string[] args)
{
var rand = new Random();
Console.WriteLine("Check DB exists...");
if (Database.Exists("BookStoreDb"))
{
Console.WriteLine("DB exists. Deleting...");
Database.Delete("BookStoreDb");
}
else
{
Console.WriteLine("DB does not exist. Skip deleting.");
}
using (var db = new Db())
{
Console.WriteLine("Creating DB..");
object tmp = db.Users.ToArray();
Console.WriteLine("Branches..");
var br1 = new Branch()
{
Address = "Mira prospect, 11 - 21",
Name = "Booko na Mira"
};
var br2 = new Branch()
{
Address = "Ulica Vzletnaya, 22",
Name = "Booko na Vzletke"
};
db.Branches.Add(br1);
db.Branches.Add(br2);
db.SaveChanges();
Console.WriteLine("Creating employees and users..");
var admin = new Employee
{
Branch = br1,
FirstName = "Admin",
MiddleName = "Admin",
LastName = "Admin",
User = new User()
{
LastLoginTime = DateTime.Now,
Login = "admin",
Password = PasswordManager.CreateHash("admin"),
Role = Role.Admin
}
};
var ivanov = new Employee
{
Branch = br1,
FirstName = "Ivan",
MiddleName = "Ivanovich",
LastName = "Ivanov",
User = new User()
{
LastLoginTime = DateTime.Now,
Login = "iii",
Password = PasswordManager.CreateHash("iii"),
Role = Role.User
}
};
var petrov = new Employee
{
Branch = br2,
FirstName = "Petr",
MiddleName = "Petrovich",
LastName = "Petrov",
User = new User()
{
LastLoginTime = DateTime.Now,
Login = "ppp",
Password = PasswordManager.CreateHash("ppp"),
Role = Role.User
}
};
var sidorov = new Employee
{
Branch = br2,
FirstName = "Sidor",
MiddleName = "Sidorovich",
LastName = "Sidorov",
User = null
};
db.Employees.Add(admin);
db.Employees.Add(ivanov);
db.Employees.Add(petrov);
db.Employees.Add(sidorov);
db.SaveChanges();
Console.WriteLine("Customers..");
//.........这里部分代码省略.........
示例8: InitData
public static void InitData(Db db)
{
_locations = new List<TestLocaion>
{
new TestLocaion()
{
Lon = 118.797655,
Lat = 32.041222,
Name = "中央饭店"
},
new TestLocaion()
{
Lon = 118.797269,
Lat = 32.044278,
Name = "总统府"
},
new TestLocaion()
{
Lon = 118.798642,
Lat = 32.048352,
Name = "雄狮国际大厦"
},
new TestLocaion()
{
Lon = 118.804479,
Lat = 32.051698,
Name = "金鹏饭店"
},
new TestLocaion()
{
Lon = 118.81701,
Lat = 32.060573,
Name = "白马公园"
}
};
foreach (var loc in _locations)
{
db.Hotels.Add(new Hotel()
{
Geo = DbGeography.PointFromText($"Point({loc.Lon} {loc.Lat})", 4326),
Name = loc.Name
});
}
db.SaveChanges();
}
示例9: AddComment
public void AddComment(string creator, string text)
{
if (string.IsNullOrEmpty(text))
return; //we don't accept empty comments
using (var context = new Db())
{
var comment = new Comment
{
Creator = creator,
DateOfCreation = DateTime.Now.ToUniversalTime(),
Text = text,
IssueId = Id
};
context.Comments.Add(comment);
context.SaveChanges();
}
}
示例10: AddAttachment
public void AddAttachment(string creator, string niceName, string base64, HttpServerUtility server)
{
var extension = Path.GetExtension(niceName);
var path = Path.Combine(server.MapPath(IssueTrackerSettings.AttachmentsPath), Guid.NewGuid().ToString() + extension);
var bytes = Convert.FromBase64String(base64);
File.WriteAllBytes(path, bytes);
using (var context = new Db())
{
var comment = new Comment
{
Creator = creator,
DateOfCreation = DateTime.Now.ToUniversalTime(),
IssueId = Id,
Text = "",
AttachmentFileName = Path.GetFileName(path),
AttachmentNiceName = niceName
};
context.Comments.Add(comment);
context.SaveChanges();
}
}
示例11: SaveModel
/// <summary>
/// Saves the given model.
/// </summary>
/// <param name="model">The model</param>
/// <param name="publish">The state of the model</param>
private static void SaveModel(Piranha.Models.Manager.PageModels.EditModel model, bool publish) {
var js = new JavaScriptSerializer();
using (var db = new Db()) {
var translation = db.PageTranslations
.Include(p => p.Regions)
.Where(p => p.PageId == model.Page.Id && p.IsDraft != publish)
.SingleOrDefault();
if (translation == null) {
translation = new Entities.PageTranslation() {
Id = Guid.NewGuid(),
PageId = model.Page.Id,
IsDraft = !publish,
Culture = CultureInfo.CurrentUICulture.Name
};
db.PageTranslations.Add(translation);
}
// Map page values
translation.Title = model.Page.Title;
translation.NavigationTitle = model.Page.NavigationTitle;
translation.Keywords = model.Page.Keywords;
translation.Description = model.Page.Description;
// Delete old region translations for simplicity
while (translation.Regions.Count > 0)
db.RegionTranslations.Remove(translation.Regions[0]);
// Map regions
for (var n = 0; n < model.Regions.Count; n++) {
var region = model.Regions[n];
var reg = new Entities.RegionTranslation() {
Id = Guid.NewGuid(),
PageId = translation.Id,
RegionId = region.Id,
TemplateId = region.RegiontemplateId,
IsDraft = !publish,
Type = region.Body.GetType().FullName,
Culture = CultureInfo.CurrentUICulture.Name
};
translation.Regions.Add(reg);
if (region.Body is IHtmlString)
reg.Body = ((IHtmlString)region.Body).ToHtmlString();
else reg.Body = js.Serialize(region.Body);
}
db.SaveChanges();
}
}
示例12: SaveBranches
public void SaveBranches(TreeNodeCollection treeNodes, Db dbSession)
{
var currentBranches = dbSession.Branches;
var hasBeenChecked = GetAllCheckedNodes(treeNodes);
var toSave = hasBeenChecked.Cast<Branch>().Where(x => !currentBranches.Any(y => y.Value == x.Text)).ToList();
dbSession.SaveChanges();
foreach (var node in toSave)
dbSession.Branches.Add(new BranchStore { Value = node.Text, MergeTo = node.MergeTo});
foreach (var currentBranch in currentBranches)
{
if (hasBeenChecked.FirstOrDefault(x => x.Text == currentBranch.Value) == null)
dbSession.Branches.Remove(currentBranch);
}
foreach (var configuration in dbSession.SystemConfiguration)
dbSession.SystemConfiguration.Remove(configuration);
dbSession.SaveChanges();
dbSession.SystemConfiguration.Add(this);
dbSession.SaveChanges();
}
示例13: SaveOrUpdate
public SaveResult<Event> SaveOrUpdate(Event e)
{
using (var db = new Db())
{
if (e.Id != 0)
{
var ev = db.Events.FirstOrDefault(x => x.Id == e.Id);
ev.Title = e.Title;
ev.StartTime = e.StartTime;
ev.EndTime = e.EndTime;
ev.IsPrivate = e.IsPrivate;
ev.Description = e.Description;
ev.Location = e.Location;
ev.FinishedGettingPosts = e.FinishedGettingPosts;
ev.IsActive = e.IsActive;
ev.PollIsActive = e.PollIsActive;
if (e.Guests != null)
{
foreach (var i in e.Guests)
{
i.Guest = db.Users.FirstOrDefault(x => x.Id == i.GuestId);
if (i.Id != 0)
{
db.Entry<Invitation>(i).State = EntityState.Modified;
}
else
{
ev.Guests.Add(i);
db.Entry<Invitation>(i).State = EntityState.Added;
}
}
}
if (e.Posts != null)
{
foreach (var p in e.Posts)
{
if (p.Id == 0)
{
p.From = db.Users.FirstOrDefault(x => x.Id == p.From.Id);
ev.Posts.Add(p);
db.Entry<Post>(p).State = EntityState.Added;
db.Entry<User>(p.From).State = EntityState.Modified;
}
if (p.Comments != null)
{
foreach (var c in p.Comments)
{
if (c.Id == 0)
{
c.From = db.Users.FirstOrDefault(x => x.Id == c.From.Id);
ev.Posts.FirstOrDefault(x => x.Id == p.Id).Comments.Add(c);
db.Entry<Post>(c).State = EntityState.Added;
db.Entry<User>(c.From).State = EntityState.Modified;
}
}
}
}
}
if (e.Votes != null)
{
foreach (var v in e.Votes)
{
if (v.Id != 0)
{
db.Entry<Vote>(v).State = EntityState.Modified;
}
else
{
ev.Votes.Add(v);
db.Entry<Vote>(v).State = EntityState.Added;
}
}
}
db.Entry<Event>(ev).State = EntityState.Modified;
db.Entry<User>(ev.Owner).State = EntityState.Unchanged;
}
else
{
e.Owner = db.Users.FirstOrDefault(x => x.Id == e.Owner.Id);
db.Events.Add(e);
}
db.SaveChanges();
}
return new SaveResult<Event>(true, e);
}