实体框架不正确的种子

时间:2017-05-18 20:54:01

标签: c# entity-framework csvhelper

我有2个简单的模型类:

public class Category
{
    public int Id { get; set; }
    public string Description { get; set; }

    public ICollection<SubCategory> SubCategories { get; set; }
}

public class SubCategory
{
    public int Id { get; set; }
    public string Description { get; set; }

    public Category Category { get; set; }
}

一个简单的背景:

public class SeederContext : DbContext
{
    public DbSet<Category> Categories { get; set; }
    public DbSet<SubCategory> SubCategories { get; set; }
}

我正在尝试播种以下csv文件

BetCategories.csv

Id,Description
1,Sports
2,Politics

BetSubCategories

Id,Category_Id,Description
1,1,Soccer
2,1,Basketball
3,1,Tennis
4,1,Poker
5,2,Election

我使用CsvHelper制作播种机:

public void Seed(SeederContext context)
{
    SeedTable<Category>("../../Data/BetCategories.csv", t =>
    {
        context.Categories.AddOrUpdate(c => c.Id, t);
        context.SaveChanges();
    });

    SeedTable<SubCategory>("../../Data/BetSubCategories.csv", t =>
    {
        context.SubCategories.AddOrUpdate(c => new { c.Description}, t);
        context.SaveChanges();
    });
}

public void SeedTable<T>(string path, Action<T[]> callback)
{
    var filename = path;

    if (filename != null)
        using (var reader = new StreamReader(filename, Encoding.UTF8))
        {
            var csvReader = new CsvReader(reader);
            csvReader.Configuration.WillThrowOnMissingField = false;
            var list = csvReader.GetRecords<T>().ToArray();
            callback(list);
        }
}

播种子类别时会出现问题。

在第一个种子(类别)上,它就可以了,并且有2个类别被写入数据库。

在第二个种子上,SubCategories正常,5个子类别被写入数据库。但是,它们也被写入Categories表 - 所以现在我总共有2 + 5 = 7个类别。

我不确定我做错了什么。

这是一个非常简单的代码优先,完全没有配置。

请告知。

小更新

手动执行种子时 - 它可以正常工作

SeedTable<Category>("../../Data/BetCategories.csv", t =>
{
    context.Categories.AddOrUpdate(c => c.Id, t);
    context.SaveChanges();
});

var subCategory = new SubCategory
{
    Category = context.Categories.FirstOrDefault(c => c.Description == "Sports"),
    Description = "Soccer"
};

context.SubCategories.AddOrUpdate(c => c.Description, subCategory);
context.SaveChanges();

subCategory = new SubCategory
{
    Category = context.Categories.FirstOrDefault(c => c.Description == "Sports"),
    Description = "Basketball"
};

context.SubCategories.AddOrUpdate(c => c.Description, subCategory);
context.SaveChanges();

1 个答案:

答案 0 :(得分:0)

我想知道这是否会解决

public class SubCategory
{
    public int Id { get; set; }
    [ForeignKey("Category")]
    public int CategoryId { get; set; }
    public string Description { get; set; }

    public virtual Category Category { get; set; }
}