Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class User : IValidatableObject
- {
- public string Name{get;set;}
- [Required]
- public DateTime CreationDate{get;set;}
- public DateTime UpdatedOnDate{get;set;}
- public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
- {
- if(Name="abc")
- {
- yield return new ValidationResult("please choose any other name then abc", new[] { "Name" });
- }
- }
- }
- User u = new User();
- u.Name = "Some name";
- u.CreationDate = DateTime.Now
- dbContext.Users.Add(u);
- dbContext.SaveChanges();
- // class structure that I am looking for
- public class User : IValidatableObject,IMyCustomInterFace
- {
- //rest codes as above class
- public void MyMethod(Whatever)
- {
- //this method gets called after Validate() and before save
- if(dataContext.Entry<User>(this).State == System.Data.EntityState.Added)
- {
- //add creation date_time
- this.CreationDate=DateTime.Now;
- //SET MORE DEFAULTS
- }
- if(dataContext.Entry<User>(this).State == System.Data.EntityState.Modified)
- {
- //update Updation time
- this.UpdatedOnDate=DateTime.Now;
- }
- }
- }
- User u = new User();
- u.Name = "Some name";
- dbContext.Users.Add(u);
- dbContext.SaveChanges();
- User u = getUserFromSomeWhere();
- u.Name = "Updated Name";
- dataContext.Entry<User>(u).State = System.Data.EntityState.Modified;
- dbContext.SaveChanges();
- public interface IHasTimeStamp
- {
- void DoTimeStamp();
- }
- Public class User : IHasTimeStamp
- (
- public void DoTimeStamp()
- {
- if(dataContext.Entry<User>(this).State == System.Data.EntityState.Added)
- {
- //add creation date_time
- this.CreationDate=DateTime.Now;
- }
- if(dataContext.Entry<User>(this).State == System.Data.EntityState.Modified)
- {
- //update Updation time
- this.UpdatedOnDate=DateTime.Now;
- }
- }
- }
- public partial class MyEntities
- {
- partial void OnContextCreated()
- {
- // Register the handler for the SavingChanges event.
- this.SavingChanges
- += new EventHandler(context_SavingChanges);
- }
- // SavingChanges event handler.
- private static void context_SavingChanges(object sender, EventArgs e)
- {
- // Validate the state of each entity in the context
- // before SaveChanges can succeed.
- foreach (ObjectStateEntry entry in
- ((ObjectContext)sender).ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified))
- {
- if (!entry.IsRelationship && (entry.Entity is IHasTimeStamp))
- {
- (entry.Entity as IHasTimeStamp).DoTimeStamp();
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment