本文整理汇总了C#中DataContext.SaveChanges方法的典型用法代码示例。如果您正苦于以下问题:C# DataContext.SaveChanges方法的具体用法?C# DataContext.SaveChanges怎么用?C# DataContext.SaveChanges使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类DataContext
的用法示例。
在下文中一共展示了DataContext.SaveChanges方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetDefaultHtml
public string GetDefaultHtml()
{
var defaultForm = new DynamicForm()
{
ActionUrl = _defaultPostUrl,
IsAjaxForm = true,
SaveFormToDatabase = true,
SendEmailOnSubmit = false
};
using (var context = new DataContext())
{
context.DynamicForms.Add(defaultForm);
context.SaveChanges();
// Now we have an id to generat a label off of
defaultForm.FormLabel = "Custom Form " + defaultForm.DynamicFormId;
// Use the id for the generated id
defaultForm.FormHtml = getDefaultFormHtml(defaultForm.DynamicFormId);
context.SaveChanges();
}
return defaultForm.FormHtml;
}
示例2: GetTagsFromString
//, DataContext db)
public List<Tag> GetTagsFromString(String StringOfTags)
{
using (var db = new DataContext("DBShop"))
{
String[] StrTags = StringOfTags.ToLower().Split(new Char[] { ' ' });
List<Tag> list = new List<Tag>();
foreach (var tag in StrTags)
{
var tags = db.Tags.Where(s => s.Name == tag);
if (tags.Count() == 0)
{
db.Tags.Add(new Tag { Name = tag, Value = 1 });
db.SaveChanges();
}
else
{
tags.ToList()[0].Value++;
db.SaveChanges();
}
list.Add(db.Tags.FirstOrDefault(s => s.Name == tag));
}
return list;
}
}
示例3: AddCategory
public static void AddCategory()
{
using (var dbContext = new DataContext("DBShop1"))
{
Category cat1 = new Category() { CategoryId = 1, Name = category1, Parent = null };
Category cat2 = new Category() { CategoryId = 2, Name = category1, Parent = cat1 };
Category cat3 = new Category() { CategoryId = 3, Name = category1, Parent = cat1 };
dbContext.Categories.Add(cat1);
dbContext.Categories.Add(cat2);
dbContext.Categories.Add(cat3);
dbContext.SaveChanges();
Assert.AreEqual(3, dbContext.Categories.Count());
dbContext.Categories.Remove(cat2);
dbContext.SaveChanges();
Assert.AreEqual(2, dbContext.Categories.Count());
dbContext.Categories.Remove(cat3);
dbContext.SaveChanges();
Assert.AreEqual(1, dbContext.Categories.Count());
dbContext.Categories.Remove(cat1);
dbContext.SaveChanges();
Assert.AreEqual(0, dbContext.Categories.Count());
}
}
示例4: EditContentViewModel
public EditContentViewModel(int id)
{
using (var context = new DataContext())
{
ThePage = context.ContentPages.Where(x => x.ContentPageId == id).Take(1).FirstOrDefault();
// If we are editing a draft, we actually need to be editing the parent page, but keep the drafts contents (html, css, meta, etc).
// To accomplish this, we can simply change the id of the page we're editing in memory, to the parent page.
BasePageId = ThePage.IsRevision ? Convert.ToInt32(ThePage.ParentContentPageId) : ThePage.ContentPageId;
var userName = Membership.GetUser().UserName;
UseWordWrap = context.Users.FirstOrDefault(x => x.Username == userName).ContentAdminWordWrap;
SiteUrl = HTTPUtils.GetFullyQualifiedApplicationPath();
// Take care of any legacy pages that don't have a publish date associated
if (ThePage.PublishDate == null)
{
ThePage.PublishDate = DateTime.Now;
context.SaveChanges();
}
// Take care of any legacy pages where Unparsed html was not saved
if (String.IsNullOrEmpty(ThePage.HTMLUnparsed) && !String.IsNullOrEmpty(ThePage.HTMLContent))
{
ThePage.HTMLUnparsed = ThePage.HTMLContent;
}
// Set a permalink if one hasn't been created / legacy support for DisplayName
if (String.IsNullOrEmpty(ThePage.Permalink))
{
ThePage.Permalink = ContentUtils.GetFormattedUrl(ThePage.DisplayName);
context.SaveChanges();
}
// Set Page Title if one hasn't been created / legacy support for DisplayName
if (String.IsNullOrEmpty(ThePage.Title))
{
ThePage.Title = ThePage.DisplayName;
context.SaveChanges();
}
// Check to see if there is a newer version available
var newerVersion = context.ContentPages.Where(x => (x.ParentContentPageId == BasePageId || x.ContentPageId == BasePageId) && x.PublishDate > ThePage.PublishDate && x.ContentPageId != ThePage.ContentPageId).OrderByDescending(x => x.PublishDate).FirstOrDefault();
if (newerVersion != null)
{
IsNewerVersion = true;
NewerVersionId = newerVersion.ContentPageId;
}
Templates = new ContentTemplates().Templates;
Revisions = context.ContentPages.Where(x => x.ParentContentPageId == BasePageId || x.ContentPageId == BasePageId).OrderByDescending(x => x.PublishDate).ToList();
// Get list of schemas for drop down
Schemas = context.Schemas.ToList();
}
}
示例5: when_using_ef
public when_using_ef()
{
var mapperContainer =
new MapperContainer()
.Register<Person, PersonEntity>(
(f, t, c) =>
{
c.Map(f.Name, () => t.Name);
c.MapAll(f.Addresses, () => t.Addresses);
})
.Register<Name, NameEntity>(
(f, t, c) =>
{
t.First = f.First;
t.Last = f.Last;
}
)
.Register<Address, AddressEntity>(
(f, t, c) => { t.Name = f.Name; }
);
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DataContext>());
_dataContext = new DataContext(mapperContainer);
_from = new Person
{
Name = new Name {First = "Person"},
Addresses = new[]
{
new Address {Name = "Keep"},
new Address {Name = "New"}
}
};
_to = _dataContext.Create<PersonEntity>();
_to.Name = new NameEntity {First = "Overwite"};
_to.Addresses = new[]
{
new AddressEntity {Name = "Keep"},
new AddressEntity {Name = "Delete"}
};
_dataContext.SaveChanges();
var personId = _to.Id;
_dataContext.Map(_from, () => _to);
_dataContext.SaveChanges();
_dataContext = new DataContext(mapperContainer);
_to = _dataContext
.People.Include(p => p.Addresses)
.Single(p => p.Id == personId);
}
示例6: CreateOk
public ActionResult CreateOk(CommentModel model)
{
int placeId = (int)(this.Session["placeId"] ?? 0);
if (ModelState.IsValid)
{
var context = new DataContext();
var username = this.HttpContext.User.Identity.Name;
var user = context.Users.Where(u => u.UserName == username).FirstOrDefault();
var place = context.Places.Where(x => x.Id == placeId).FirstOrDefault();
if (place == null)
{
ModelState.AddModelError("Place", "Ivalid place id!");
}
if (user == null)
{
ModelState.AddModelError("User", "Ivalid user!");
}
Comment comment = new Comment()
{
Text = model.Text,
User = user
};
place.Comments.Add(comment);
context.SaveChanges();
return PartialView("_Success");
}
return PartialView("_Create", model);
}
示例7: TestInitialize
public virtual void TestInitialize()
{
using (var dataContext = new DataContext())
{
var queryAllLanguages =
from language in dataContext.Languages
select language;
if (queryAllLanguages.ToList().Count > 0)
{
foreach (var language in queryAllLanguages)
{
dataContext.Languages.Remove(language);
}
}
var queryAllKeywords =
from keyword in dataContext.Keywords
select keyword;
if (queryAllKeywords.ToList().Count > 0)
{
foreach (var keyword in queryAllKeywords)
{
dataContext.Keywords.Remove(keyword);
}
}
dataContext.SaveChanges();
}
}
示例8: Insert
public JsonData Insert(Country entity, string userId)
{
try
{
using (var db = new DataContext())
{
if (entity == null) throw new ArgumentNullException("The new" + " record is null");
var newData = new Country
{
Name = entity.Name,
Description = entity.Description,
ShortCode = entity.ShortCode,
Updated = DateTime.Now,
Created = DateTime.Now,
IsActive = true,
IsDeleted = false,
CreatedById = userId,
UpdatedById = userId
};
db.Countries.Add(newData);
db.SaveChanges();
return DataHelpers.ReturnJsonData(newData, true, "Saved successfully", 1);
}
}
catch (Exception e)
{
return DataHelpers.ExceptionProcessor(e);
}
}
示例9: Insert
public JsonData Insert(AgentBranch entity, string userId)
{
try
{
using (var db = new DataContext())
{
if (entity == null) throw new ArgumentNullException("The new" + " record is null");
var newData = new AgentBranch
{
BranchId = entity.BranchId,
AgentId = entity.AgentId,
Updated = DateTime.Now,
Created = DateTime.Now,
IsActive = true,
IsDeleted = false,
CreatedById = userId,
UpdatedById = userId
};
db.AgentBranches.Add(newData);
db.SaveChanges();
return DataHelpers.ReturnJsonData(newData, true, "Saved successfully", 1);
}
}
catch (Exception e)
{
return DataHelpers.ExceptionProcessor(e);
}
}
示例10: EditBlogViewModel
public EditBlogViewModel(string blogId)
{
BlogId = Int32.Parse(blogId);
_memUser = Membership.GetUser(HttpContext.Current.User.Identity.Name);
SiteUrl = HTTPUtils.GetFullyQualifiedApplicationPath() + "blog/";
using (var context = new DataContext())
{
ThisBlog = context.Blogs.FirstOrDefault(x => x.BlogId == BlogId);
// Make sure we have a permalink set
if (String.IsNullOrEmpty(ThisBlog.PermaLink))
{
ThisBlog.PermaLink = ContentUtils.GetFormattedUrl(ThisBlog.Title);
context.SaveChanges();
}
// Get the list of Authors for the drop down select
BlogUsers = context.BlogUsers.Where(x => x.IsActive == true).OrderBy(x => x.DisplayName).ToList();
Categories = context.BlogCategories.Where(x => x.IsActive == true).ToList();
UsersSelectedCategories = new List<string>();
_thisUser = context.Users.FirstOrDefault(x => x.Username == _memUser.UserName);
}
// Get the admin modules that will be displayed to the user in each column
getAdminModules();
}
示例11: SiteSettingsViewModel
public Dictionary<int, bool> SiteRetensionTimeValues; // Count / IsSelected
#endregion Fields
#region Constructors
public SiteSettingsViewModel()
{
using (var context = new DataContext())
{
Settings = context.SiteSettings.FirstOrDefault();
// Set some initial values if none are found.
if (Settings == null)
{
Settings = new SiteSettings()
{
SearchIndex = true
};
context.SiteSettings.Add(Settings);
context.SaveChanges();
}
}
SiteRetensionTimeValues = new Dictionary<int, bool>
{
{ 5, Settings.ContentPageRevisionsRetensionCount == 5 },
{ 10, Settings.ContentPageRevisionsRetensionCount == 10 },
{ 25, Settings.ContentPageRevisionsRetensionCount == 25 },
{ 50, Settings.ContentPageRevisionsRetensionCount == 50 }
};
RolesList = Roles.GetAllRoles().ToList();
}
示例12: AddCity
public bool AddCity(string email, string city, int quantity)
{
var userId = this.GetUserId(email);
try
{
using (var context = new DataContext())
{
var weatherElement = context.Table<Mashup.Data.Model.Weather>().NewRow();
weatherElement.ID_user = userId;
weatherElement.City = city;
weatherElement.Quantity = quantity;
context.Table<Mashup.Data.Model.Weather>().Insert(weatherElement);
context.SaveChanges();
return true;
}
}
catch (Exception)
{
//ojojojo
}
return false;
}
示例13: Insert
public JsonData Insert(IdentityRole entity, string userId)
{
try
{
using (var db = new DataContext())
{
if (entity == null) throw new ArgumentNullException("The new" + " record is null");
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));
//Create Roles if they do not exist
if (!roleManager.RoleExists(entity.Name))
{
roleManager.Create(new IdentityRole(entity.Name));
}
db.SaveChanges();
return DataHelpers.ReturnJsonData(entity, true, "Saved successfully", 1);
}
}
catch (Exception e)
{
return DataHelpers.ExceptionProcessor(e);
}
}
示例14: Update
public JsonData Update(IdentityRole entity, string userId)
{
try
{
using (var db = new DataContext())
{
if (entity == null) throw new ArgumentNullException("The new" + " record is null");
//var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));
//Update Role Roles if they do not exist
var role = db.Roles.FirstOrDefault(x => x.Id == entity.Id);
if (role != null)
{
role.Name = entity.Name;
//roleManager.Update(role);
}
db.SaveChanges();
return DataHelpers.ReturnJsonData(entity, true, "Updated successfully", 1);
}
}
catch (Exception e)
{
return DataHelpers.ExceptionProcessor(e);
}
}
示例15: AddCategory
public JsonResult AddCategory(string name)
{
var result = new JsonResult();
if (!String.IsNullOrEmpty(name))
{
using (var context = new DataContext())
{
var newCategory = new BlogCategory
{
CategoryName = name,
CreateDate = DateTime.Now,
IsActive = true
};
context.BlogCategories.Add(newCategory);
context.SaveChanges();
result.Data = new {id = newCategory.CategoryId};
return result;
}
}
return result;
}