什么是EF的一流机制?

时间:2015-06-15 21:42:29

标签: c# asp.net entity-framework asp.net-core-mvc

在ASP.NET MVC 6的MusicStore示例项目中的EF Datastore示例数据中。

有评论

“// TODO [EF]这可以用EF”

中的第一类机制代替

https://github.com/aspnet/MusicStore/blob/master/src/MusicStore.Spa/Models/SampleData.cs

什么是一流的机制?我知道有代码优先,但似乎与此无关,在第一堂课时找不到任何东西。

评论中提到的代码。

        // TODO [EF] This may be replaced by a first class mechanism in EF
    private static async Task AddOrUpdateAsync<TEntity>(
        IServiceProvider serviceProvider,
        Func<TEntity, object> propertyToMatch, IEnumerable<TEntity> entities)
        where TEntity : class
    {
        // Query in a separate context so that we can attach existing entities as modified
        List<TEntity> existingData;
        using (var db = serviceProvider.GetService<MusicStoreContext>())
        {
            existingData = db.Set<TEntity>().ToList();
        }

        using (var db = serviceProvider.GetService<MusicStoreContext>())
        {
            foreach (var item in entities)
            {
                db.Entry(item).State = existingData.Any(g => propertyToMatch(g).Equals(propertyToMatch(item)))
                    ? EntityState.Modified
                    : EntityState.Added;
            }

            await db.SaveChangesAsync();
        }
    }

0 个答案:

没有答案