0

我正在为我的开发数据库添加一些种子数据。我所拥有的似乎相当笨重,有没有办法使用某种 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);
    }
}
4

2 回答 2

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));
于 2012-06-03T12:11:01.283 回答
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

于 2012-06-03T14:03:53.940 回答