Skip to content

Instantly share code, notes, and snippets.

@jfoshee
Created May 9, 2014 21:03
Show Gist options
  • Save jfoshee/922008547cb97288bf21 to your computer and use it in GitHub Desktop.
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.
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