使用列表或集合使用EF Code First对数据进行种子设定

时间:2012-06-03 11:33:47

标签: c# .net asp.net-mvc-3 ienumerable ilist

我正在为我的开发数据库添加一些种子数据。我有什么看起来相当笨重,有没有办法使用某种IEnumerable类型,如List或也许集合,以使这更容易?

public class MusicDBInit : DropCreateDatabaseIfModelChanges<MusicContext>
{
    protected override void Seed(MusicContext db)
    {
        Band bvs = new Band { Name = "Bear vs Shark", Members = 4 };
        Band circa = new Band { Name = "Circa Survive", Members = 4 };
        Band dam = new Band { Name = "Damiera", Members = 3 };

        db.Bands.Add(bvs);
        db.Bands.Add(circa);
        db.Bands.Add(dam);

        base.Seed(db);
    }
}

2 个答案:

答案 0 :(得分:1)

尝试这样的事情(如Online Music Store MVC Sample中所做的那样:

 var bands = new List<Band>{
                     new Band { Name = "Bear vs Shark", Members = 4 },
                     new Band { Name = "Circa Survive", Members = 4 },
                     new Band { Name = "Damiera", Members = 3 }
 };


bands.ForEach(x=> db.Bands.Add(x));

答案 1 :(得分:1)

我通常遵循的另一种方法是从XML文件加载种子数据。一个单独的类将具有以下内容:

    private XmlNodeList readNodes(String xmlFilePath, String nodeName)
    {
        FileStream reader = new FileStream(xmlFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        System.Xml.XmlDocument source = new System.Xml.XmlDocument();
        source.Load(reader);
        return source.GetElementsByTagName(nodeName);
    }

    public List<Band> readBands(String xmlFilePath)
    {
        List<Band> results = new List<Band>();
        foreach (XmlNode node in readNodes(xmlFilePath, "Band"))
        {
            results.Add(new Band { Members = node.Attributes["members"].Value, Name = node.Attributes["name"].Value });
        }
        results.Sort();
        return results;
    }

然后将以下内容添加到您的Seed方法中:

    foreach (Band b in seeder.readBands(AppDomain.CurrentDomain.BaseDirectory + "App_Data\\Bands.xml"))
    {
        db.bands.Add(b);
    }

您的XML看起来像这样,位于App_Data目录下。

<?xml version="1.0" encoding="UTF-8"?>
<bands>
    <band name="Bear vs Shark" members="4" />
    <band name="Circa Survive" members="4" />
    <band name="Damiera" members="3" />
</bands>

然后,您可以为要播种的每个表创建种子方法和XML文件。请记住,由于您使用的是Add而不是AddOrUpdate,因此只要Seed运行,您就很有可能会添加副本。