Created
May 9, 2014 21:03
-
-
Save jfoshee/922008547cb97288bf21 to your computer and use it in GitHub Desktop.
Sorts ServiceStack.OrmLite POCO table definitions so they can be created without violating foreign key constraints using QuickGraph's topological sort.
This file contains 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.Linq; | |
using QuickGraph; | |
using QuickGraph.Algorithms; | |
using ServiceStack.OrmLite; | |
namespace Gists | |
{ | |
public static class CodeFirstDatabase | |
{ | |
/// Sorts table definitions so they can | |
/// be created without violating foreign key constraints | |
public static IEnumerable<Type> CreationOrder(IEnumerable<Type> tableDefinitions) | |
{ | |
var graph = new AdjacencyGraph<Type, Edge<Type>>(); | |
graph.AddVertexRange(tableDefinitions); | |
foreach(var type in tableDefinitions) | |
{ | |
var foreignKeys = type.GetProperties() | |
.SelectMany(p => p.GetCustomAttributes(true) | |
.OfType<ForeignKeyAttribute>()); | |
foreach(var foreignKey in foreignKeys) | |
graph.AddEdge(new Edge<Type>(type, foreignKey.Type)); | |
} | |
return graph.TopologicalSort().Reverse(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment