具有实体框架代码优先的长期种子方法

时间:2015-03-18 11:13:25

标签: entity-framework-6 ef-migrations

我的Seed()方法运行得相当长。有没有办法在运行update-database命令时写入控制台?

到目前为止,Console.WriteLine()Debug.WriteLine()尚未将输出写入程序包管理器控制台。

1 个答案:

答案 0 :(得分:0)

您可以通过使用接受接口并返回上下文实例以保持流畅的方法扩展基本DbContext类来避免run-on种子方法。

虽然它没有解决无法在包管理器控制台中编写控制台/调试输出的问题,但它会告诉您哪个实体在保持整洁的同时失败了。

<强> Configuration.cs

using System.Configuration;
using MySolution.Data.Migrations.Seedings;

namespace MySolution.Data.Migrations
{
    using System.Data.Entity.Migrations;

    internal sealed class Configuration : DbMigrationsConfiguration<MySolution.Data.MySolutionContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(MySolution.Data.MySolutionContext context)
        {

            context
                .AppendSeeding<AddressSeeding>(true)
                .AppendSeeding<CustomerSeeding>(true)
                .AppendSeeding<OrderSeeding>(true)
                .AppendSeeding<ShipmentSeeding>(true)
                .AppendSeeding<ApplicationSettingsSeeding>();

        }
    }
}

<强> DbContextExtensions.cs

using System;
using System.Data.Entity;

namespace MySolution.Data.Migrations {
    public static class DbContextExtensions {

        public static DbContext AppendSeeding<T>(
            this DbContext context, bool saveChanges = false) 
            where  T : ISeeding, new() {

            var seeding = new T();

            try {
                seeding.Seed(context);
                if (saveChanges) {
                    context.SaveChanges();
                }
            }
            catch (Exception ex) {
                throw new Exception(
                    $"Unhandled exception while appending seed data via {seeding.GetType().Name}",
                    ex);
            }

            return context;

        }

    }
}

<强> ISeeding.cs

using System.Data.Entity;

namespace MySolution.Data.Migrations {
    public interface ISeeding {
        void Seed(DbContext context);
    }
}

AddressSeeding.cs(ISeeding的示例实施)

using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using MySolution.Data.Models;

namespace MySolution.Data.Migrations.Seedings {
    public class AddressSeeding : ISeeding {
        public void Seed(DbContext context) {

            ((MySolutionContext)context).Address.AddOrUpdate(
               address => new { address.Address1},
                new Address {
                    Address1 = "111 Fake St.",
                    City = "Nowhereland",
                    County = "Countyville",
                    State = "ST",
                    Zip = "12345",
                    AddressType = new AddressType {
                        Name = "Home"
                    },
                }    
            );

        }
    }
}