Entity framework split model into multiple tables programmatically

c# entity-framework entity-framework-6 sql-server

Accepted Answer

found a solution to the problem. I had to use the "dynamic" keyword and Linq Expressions:

    private static void SplitIntoTables<T>(DbModelBuilder modelBuilder, IReadOnlyCollection<PropertyInfo> properties, int columnLimit) where T : class
    {
        var numberOfTables = Math.Ceiling((properties.Count + (double)columnLimit / 2) / columnLimit);
        var paramExp = Expression.Parameter(typeof(T));

        var tableIndex = 0;
        foreach (var tableGroup in properties.GroupBy(p => p.Name.GetHashCode() % numberOfTables))
        {
            var expressions = tableGroup.Select(p => Expression.Lambda(
                typeof(Func<,>).MakeGenericType(typeof(T), p.PropertyType),
                Expression.Property(paramExp, p), paramExp));

            modelBuilder.Entity<T>().Map(m =>
            {
                foreach (var exp in expressions)
                {
                    m.Property((dynamic) exp);
                }
                m.ToTable($"{typeof(T).Name}_{++tableIndex}");
            });
        }
    }
1
6/29/2017 12:54:24 PM

Popular Answer

You tell us "don't ask." However, the fact that you're repeating it to yourself is your greatest issue. You need to find out why if your model starts to have even more fields than 50. I wonder if it wouldn't be beneficial to take a break and go over some more abstract computing principles again. I'd begin with zzz-5 zzz. I can infer from 1K dynamic characteristics that you need this badly.

By the way, "Database Normalization" ideas aren't necessarily exclusive to SQL databases. Wherever possible, you should normalise your POCO models in the same way. Undoubtedly, OO languages include certain non-relational ideas. But there is no justification for the extremes you mention.

The Design driven by domains paradigm is an alternative. Since I'm not as proficient in this as you are, I'm not suggesting that you start there. But based on my experience thus far putting it into practise, I'd say the learning curve was worthwhile.

I should be mindful to avoid being patronising. My own tables aren't precisely in the highest normal forms. But I'll admit that the headaches are worse when I don't.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow