Last active
August 29, 2015 14:11
-
-
Save mahizsas/b158d143ef578a9ba244 to your computer and use it in GitHub Desktop.
Mapping private properties with EF via conventions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.ComponentModel.DataAnnotations.Schema; | |
using System.Data.Entity; | |
using System.Data.Entity.ModelConfiguration.Conventions; | |
using System.Linq; | |
using System.Reflection; | |
namespace ConsoleApplication1.Model | |
{ | |
public class ApplicationDbContext : DbContext | |
{ | |
public ApplicationDbContext() : base("TestDb") { } | |
public IDbSet<User> Users { get; set; } | |
public IDbSet<Country> Countries { get; set; } | |
public static void SetInitializer() | |
{ | |
Database.SetInitializer(new DropAlways()); | |
} | |
protected override void OnModelCreating(DbModelBuilder modelBuilder) | |
{ | |
base.OnModelCreating(modelBuilder); | |
modelBuilder.Conventions.Add(new NonPublicColumnAttributeConvention()); | |
} | |
} | |
public class NonPublicColumnAttributeConvention : Convention | |
{ | |
public NonPublicColumnAttributeConvention() | |
{ | |
Types().Having(NonPublicProperties) | |
.Configure((config, properties) => | |
{ | |
foreach (PropertyInfo prop in properties) | |
{ | |
config.Property(prop); | |
} | |
}); | |
} | |
private static IEnumerable<PropertyInfo> NonPublicProperties(Type type) | |
{ | |
var matchingProperties = type.GetProperties(BindingFlags.SetProperty | BindingFlags.GetProperty | BindingFlags.NonPublic | BindingFlags.Instance) | |
.Where(propInfo => propInfo.GetCustomAttributes(typeof(ColumnAttribute), true).Length > 0) | |
.ToArray(); | |
return matchingProperties.Length == 0 ? null : matchingProperties; | |
} | |
} | |
public class DropAlways : DropCreateDatabaseAlways<ApplicationDbContext> | |
{ | |
protected override void Seed(ApplicationDbContext context) | |
{ | |
context.Countries.Add(new Country("Colombia", "co")); | |
base.Seed(context); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment