本文整理汇总了C#中ApplicationDbContext.Entry方法的典型用法代码示例。如果您正苦于以下问题:C# ApplicationDbContext.Entry方法的具体用法?C# ApplicationDbContext.Entry怎么用?C# ApplicationDbContext.Entry使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ApplicationDbContext
的用法示例。
在下文中一共展示了ApplicationDbContext.Entry方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: FormViewProfileInformation_UpdateItem
// The id parameter name should match the DataKeyNames value set on the control
public void FormViewProfileInformation_UpdateItem(string id)
{
var context = new ApplicationDbContext();
ForumApp.Models.ApplicationUser item = context.Users.FirstOrDefault(u => u.Id == id);
// Load the item here, e.g. item = MyDataLayer.Find(id);
if (item == null)
{
// The item wasn't found
ModelState.AddModelError("", String.Format("Item with id {0} was not found", id));
return;
}
TryUpdateModel(item);
var existingUser = context.Users.FirstOrDefault(u => u.UserName == item.UserName);
if (existingUser != null)
{
throw new ArgumentException("Username is already taken");
}
if (ModelState.IsValid)
{
// Save changes here, e.g. MyDataLayer.SaveChanges();
context.Entry(item).State = EntityState.Modified;
context.SaveChanges();
}
}
示例2: UploadProfileImage
public ActionResult UploadProfileImage(HttpPostedFileBase file)
{
if (file != null)
{
string fileName = Guid.NewGuid().ToString() + ".jpg";
string path = System.IO.Path.Combine(
Server.MapPath("~/Images/Profile"), fileName);
using (var db = new ApplicationDbContext())
{
var userId = User.Identity.GetUserId();
var currentUser = db.Users.FirstOrDefault(u => u.Id == userId);
if (currentUser.ProfileImageUri != null)
{
var success = RemoveCurrentImage(currentUser.ProfileImageUri);
}
currentUser.ProfileImageUri = fileName;
db.Entry(currentUser).State = EntityState.Modified;
db.SaveChanges();
}
// file is uploaded
file.SaveAs(path);
}
// after successfully uploading redirect the user
return RedirectToAction("EditPublicProfile");
}
示例3: GridViewMessages_RowUpdating
protected void GridViewMessages_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
using (var context = new ApplicationDbContext())
{
string contents = (this.GridViewMessages.Rows[e.RowIndex].FindControl("TextBoxContents") as TextBox).Text;
if (string.IsNullOrWhiteSpace(contents))
{
LabelErrorMessage.Text = "Contents cannot be empty";
e.Cancel = true;
return;
}
int messageId = Convert.ToInt32(this.GridViewMessages.DataKeys[e.RowIndex].Value);
var message = context.Messages.FirstOrDefault(m => m.Id == messageId);
if (message == null)
{
LabelErrorMessage.Text = "No message selected.";
e.Cancel = true;
return;
}
message.Contents = contents;
context.Entry<Message>(message).State = EntityState.Modified;
context.SaveChanges();
DataBind();
Response.Redirect(Request.RawUrl);
e.Cancel = true;
}
}
示例4: EditProfile
public async Task<ActionResult> EditProfile(ApplicationUser user)
{
ApplicationDbContext db = new ApplicationDbContext();
if (!ModelState.IsValid)
{
return View(user);
}
string userId = User.Identity.GetUserId();
ApplicationUser savedUser = db.Users.Single(x => x.Id == userId);
savedUser.FirstName = user.FirstName;
savedUser.LastName = user.LastName;
savedUser.Email = user.Email;
savedUser.UserName = user.UserName;
db.Entry(savedUser).State = EntityState.Modified;
await db.SaveChangesAsync();
FormsAuthentication.SignOut();
user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("AtAGlance", "Home");
}
示例5: SendChatMessage
public void SendChatMessage(string who, string message)
{
var name = Context.User.Identity.Name;
using (var db = new ApplicationDbContext())
{
var user = db.Useras.Find(who);
if (user == null)
{
Clients.Caller.showErrorMessage("Could not find that user.");
}
else
{
db.Entry(user)
.Collection(u => u.Connections)
.Query()
.Where(c => c.Connected == true)
.Load();
if (user.Connections == null)
{
Clients.Caller.showErrorMessage("The user is no longer connected.");
}
else
{
foreach (var connection in user.Connections)
{
Clients.Client(connection.ConnectionID)
.reciever(name + ": " + message);
}
}
}
}
}
示例6: OnConnected
public override Task OnConnected()
{
var name = Context.User.Identity.Name;
if (name != "")
{
using (var db = new ApplicationDbContext())
{
var user = db.online
.SingleOrDefault(u => u.Username == name);
if (user == null)
{
user = new OnlineUsers
{
Username = name,
Status = true
};
db.online.Add(user);
}
else
{
user.Status = true;
db.Entry(user).State = EntityState.Modified;
}
db.SaveChanges();
}
}
return base.OnConnected();
}
示例7: ChangeProfilePic
public ActionResult ChangeProfilePic(ApplicationUser user, HttpPostedFileBase fileUpload)
{
ApplicationUser applicationUser = db.Users.FirstOrDefault(x => x.UserName == User.Identity.Name);
if (applicationUser.Id != user.Id)
{
return RedirectToAction("Unauthorized", "Error");
}
if (ImageUploadValidator.IsWebFriendlyImage(fileUpload))
{
using (ApplicationDbContext db = new ApplicationDbContext())
{
//save the uploaded file
var fileName = Path.GetFileName(fileUpload.FileName);
fileUpload.SaveAs(Path.Combine(Server.MapPath("~/Images/"), fileName));
//set the users profile pic url to the appropriate field
string profilePicUrl = "~/Images/" + fileName;
user.ProfilePicUrl = profilePicUrl;
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("AtAGlance", "Home");
}
else
{
return View(user);
}
}
示例8: CouponBuyingLogic
public static HttpStatusCodeResult CouponBuyingLogic(Coupon coupon,System.Web.Mvc.ModelStateDictionary modelState,string SessionId)
{
ApplicationDbContext db = new ApplicationDbContext();
if (modelState.IsValid)
{
coupon.TotalNumberOfCoupons -= coupon.RequiredNumberOfCoupons;
coupon.Purchase++;
Buy buy = new Buy() { CouponId = coupon.CouponId, ApplicationUserId = SessionId };
db.Buys.Add(buy);
if (coupon.NuberOfCouponsToOfferManaged>0)
coupon.NuberOfCouponsToOfferManaged -= coupon.RequiredNumberOfCoupons;
db.Entry(coupon).State = EntityState.Modified;
db.SaveChanges();
if (coupon.TotalNumberOfCoupons > 0)
{
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
coupon.Acitve = false;
db.Entry(coupon).State = EntityState.Modified;
db.SaveChanges();
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
示例9: SaveCollage
public ActionResult SaveCollage(string userID, string stringedJSON, int collageID)
{
ApplicationDbContext Context = new ApplicationDbContext();
ApplicationUser User = new ApplicationUser();
foreach (var i in Context.Users)
{
if (i.UserName == userID)
User = i;
}
Collages newCollage = new Collages();
newCollage.userID = User.Id;
newCollage.collageInfo = stringedJSON;
if (collageID == 0)
{
Context.Collages.Add(newCollage);
Context.Entry(newCollage).State = System.Data.Entity.EntityState.Added;
}
else
{
Context.Collages.Find(collageID).collageInfo = stringedJSON;
}
Context.SaveChanges();
return RedirectToAction("Index");
}
示例10: Edit
public async Task<ActionResult> Edit(EditUserViewModel model)
{
var Db = new ApplicationDbContext();
var user = Db.Users.First(u => u.UserName == model.UserName);
if (ModelState.IsValid)
{
model.PhotoUrl = Utils.SavePhotoFileToDisk(model.Photo, this, user.PhotoUrl, model.IsNoPhotoChecked);
user.PhotoUrl = model.PhotoUrl;
// Update the user data:
user.FirstName = model.FirstName;
user.LastName = model.LastName;
user.Email = model.Email;
Db.Entry(user).State = System.Data.Entity.EntityState.Modified;
await Db.SaveChangesAsync();
if (HttpContext.User.IsInRole("Admin"))
{
return RedirectToAction("Index");
}
else
{
return RedirectToAction("Edit", new { id = user.UserName, Message = ManageMessageId.RegisterSuccess });
}
}
model.PhotoUrl = user.PhotoUrl;
// If we got this far, something failed, redisplay form
return View(model);
}
示例11: CreateUsersForReport
public static void CreateUsersForReport(ApplicationDbContext context, string usersstring)
{
var userManager = new ApplicationUserManager(new UserStore<User>(context));
string[][] userarray = usersstring.Split(',').Select(str => str.Split(' ')).ToArray();
foreach (var strar in userarray)
{
User usersu = userManager.FindByName(strar[0] + " " + strar[1]);
if (usersu == null)
{
usersu = new User
{
UserName = strar[0] + " " + strar[1],
FirstName = strar[1],
LastName = strar[0],
SecurityStamp = Guid.NewGuid().ToString(),
LastLoginTime = DateTime.UtcNow,
RegistrationDate = DateTime.UtcNow,
PasswordHash =
userManager.PasswordHasher.HashPassword("12345")
};
IdentityRole role = context.Roles.FirstOrDefault(r => string.Equals(r.Name, "Employee"));
if (role != null) usersu.Roles.Add(new IdentityUserRole {RoleId = role.Id, UserId = usersu.Id});
context.Entry(usersu).State = EntityState.Added;
}
}
context.SaveChanges();
}
示例12: Add
public String Add(int? id)
{
if (id == null)
return "";
ApplicationDbContext db = new ApplicationDbContext();
var u = db.AppUsers.Find(User.Identity.GetUserId());
var s = DevFestEvent.Helpers.SessionHelper.AllSessions().Where(q => q.IID == id).FirstOrDefault();
if (s == null)
return "";
u.Sessions.Add(s);
db.Entry(u).State = System.Data.Entity.EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
return "ok";
}
示例13: Update
public void Update(PieceOfNews pieceOfNews)
{
using (var context = new ApplicationDbContext())
{
context.Entry(pieceOfNews).State = EntityState.Modified;
context.SaveChanges();
}
}
示例14: Delete
public async Task<ActionResult> Delete(string id)
{
ApplicationDbContext DB = new ApplicationDbContext();
ApplicationUser user = DB.Users.Find(id);
DB.Entry(user).State = System.Data.Entity.EntityState.Deleted;
DB.SaveChanges();
return RedirectToAction("Index");
}
示例15: Update
public void Update(Entities.Project project)
{
using (var context = new ApplicationDbContext())
{
context.Entry(project).State = EntityState.Modified;
context.SaveChanges();
}
}