简体   繁体   English

实体框架6创建单个相关记录

[英]Entity Framework 6 Creating an single related record

I am using Entity Framework on a project involving TV Series. 我在涉及电视连续剧的项目上使用实体框架。 The data is loaded by loading Episode files. 通过加载情节文件来加载数据。 When I create an Episode it should find the series that it belongs to and use that one or else create a new one. 当我创建一个情节时,它应该找到它所属的系列并使用该情节,否则创建一个新情节。

I am using an "EpisodeFactory" to create the Episodes and it works until I save and then it creates a new series for each episode. 我正在使用“ EpisodeFactory”来创建情节,并且在我保存之前一直有效,然后为每个情节创建了一个新系列。

I am looking for: 我在寻找:

  • Series : Id = 01, Name = 'Gotham' 系列 :Id = 01,名称='Gotham'
  • Episode : Id = 21, Name = 'GothamS01E01', Series = 01 集数 :Id = 21,名称='GothamS01E01',系列= 01
  • Episode : Id = 22, Name = 'GothamS01E02', Series = 01 集数 :Id = 22,名称='GothamS01E02',系列= 01

What I am Getting: 我得到的是:

  • Series : Id = 01, Name = 'Gotham' 系列 :Id = 01,名称='Gotham'
  • Series : Id = 02, Name = 'Gotham' 系列 :Id = 02,名称='Gotham'
  • Series : Id = 03, Name = 'Gotham' 系列 :Id = 03,名称='Gotham'
  • Episode : Id = 21, Name = 'GothamS01E01', Series = 02 集数 :Id = 21,名称='GothamS01E01',系列= 02
  • Episode : Id = 22, Name = 'GothamS01E02', Series = 03 集数 :Id = 22,名称='GothamS01E02',系列= 03

Here is my UnitTest for this: 这是我的UnitTest:

    [Test]
    public void ShouldLoadSeriesIfOneExists()
    {
        const string testDirectory = TestContstants.TestDir + @"\ShouldLoadSeriesIfOneExists";
        var episodeFactory = new EpisodeFactory();
        var randomSeriesName = Guid.NewGuid().ToString();
        var testEpisodeA = episodeFactory.createNewEpisode(testDirectory + @"\" + randomSeriesName + @"S01E01.avi");
        var testEpisodeB = episodeFactory.createNewEpisode(testDirectory + @"\" + randomSeriesName + @"S02E03.avi");

        using (var dbContext = new MediaModelDBContext())
        {
            dbContext.Episodes.Add(testEpisodeA);
            dbContext.Episodes.Add(testEpisodeB);
            dbContext.SaveChanges();

            Assert.That(dbContext.Series.Count(s => s.SeriesName == randomSeriesName), Is.EqualTo(1));

            dbContext.Series.Remove(testEpisodeA.Series);
        }
    }

The EpisodeFactory get a file name and extracts the Episode information from the file. EpisodeFactory获取文件名,并从文件中提取Episode信息。

The Series is fetched with: 系列的作品包括:

    public Series GetSeriesBySeriesName(string seriesName)
    {
        using (var dbContext = new MediaModelDBContext())
        {
            if (dbContext.Series.Any())
            {
                var matchingSeries = dbContext.Series.FirstOrDefault(series => series.SeriesName == seriesName);
                if (matchingSeries != null) return matchingSeries;
            }

            var seriesByShowName = new Series(){SeriesName = seriesName};
            dbContext.Series.Add(seriesByShowName);
            dbContext.SaveChanges();
            return seriesByShowName;
        }
    }

And the relevant model: 和相关模型:

public class Episode
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity), Key]
    public virtual int EpisodeId { get; set; }
    public virtual Series Series { get; set; }

    // ...

}

public class Series
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity), Key]
    public int SeriesId { get; set; }
    public string SeriesName { get; set; }
    public ObservableCollection<Episode> Episodes { get; set; }

    public Series()
    {
    }

    // ...
}

Are you sharing the same DBContext Instance in test and Factory? 您是否在测试和工厂中共享相同的DBContext实例? If not this is the problem that you are using difererent DBContext Instances in your factory method and in your test. 如果不是,这就是您在工厂方法和测试中使用不同DBContext实例的问题。

If you use different DBContext instances Entity Framework is not able to kwnow that series object exist in database, series become a deattached object for the DBContest instance in your test (google for deattached entity framework) 如果您使用不同的DBContext实例,则实体框架无法知道数据库中存在系列对象,那么系列将成为测试中DBContest实例的脱离对象(适用于脱离实体框架的Google)

You have to share the same DBContext instance across test and factory, or work with series as deatthaced object. 您必须在测试和工厂之间共享相同的DBContext实例,或者将系列用作已分离对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM