Skip to content

Instantly share code, notes, and snippets.

@svrooij
Created June 15, 2016 13:05
Show Gist options
  • Save svrooij/23407bc3138a08f915e06220e6a1000e to your computer and use it in GitHub Desktop.
Save svrooij/23407bc3138a08f915e06220e6a1000e to your computer and use it in GitHub Desktop.
EntityFramework default properties
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel;
namespace YourNamespace
{
[Table("Blogs")]
// We inherit the EntityBase class here (with Id, CreatedAt and UpdatedAt)
public class Blog : EntityBase
{
[MaxLength(150)]
[Required]
public string Name { get; set; }
[Required]
[DataType(DataType.MultilineText)]
public string Text { get; set;}
}
}
using System;
using System.Linq;
using System.Data.Entity;
namespace YourNamespace
{
public class BlogsDatabase : DbContext
{
public InternshipDatabase() : base("BlogsDB") { }
public DbSet<Blog> Blogs { get; set; }
// Lets override the default save changes, so we automaticaly change the UpdatedAt field.
public override int SaveChanges()
{
foreach (var entry in ChangeTracker.Entries().Where(x => x.Entity.GetType().GetProperty("CreatedAt") != null))
{
if (entry.State == EntityState.Added)
{
entry.Property("CreatedAt").CurrentValue = DateTime.Now;
}
else if (entry.State == EntityState.Modified)
{
// Ignore the CreatedTime updates on Modified entities.
entry.Property("CreatedAt").IsModified = false;
}
// Always set UpdatedAt. Assuming all entities having CreatedAt property
// Also have UpdatedAt
entry.Property("UpdatedAt").CurrentValue = DateTime.Now;
}
return base.SaveChanges();
}
}
}
using System;
using System.ComponentModel.DataAnnotations;
namespace YourNamespace
{
public class EntityBase
{
[Key]
public Guid Id { get; set; } = Guid.NewGuid();
public DateTime? CreatedAt { get; set; } = DateTime.Now;
public DateTime? UpdatedAt { get; set; } = DateTime.Now;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment