سؤال

I'm adding some seed data for my development database. What I have seems rather clunky, is there a way to use some sort of IEnumerable type such as List or perhaps collection to make this easier?

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);
    }
}
هل كانت مفيدة؟

المحلول

Try something like this (as done in 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));

نصائح أخرى

An alternative that I usually follow is to load in seed data from XML files. A separate class would hold the following:

    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;
    }

Then add the following to your Seed method:

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

Your XML would then look something like this and be located under your App_Data directory.

<?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>

You could then create seed methods and XML files for every table you'd like to seed. And remember that since you're using Add rather than AddOrUpdate you will most likely be adding duplicate whenever Seed runs.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top