1
0
mirror of https://github.com/ppy/osu.git synced 2024-09-24 16:07:25 +08:00
osu-lazer/osu.Game/Database/DatabaseBackedStore.cs

53 lines
2.0 KiB
C#
Raw Normal View History

2018-01-05 19:21:19 +08:00
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
2017-10-25 21:07:32 +08:00
using System.Linq;
using Microsoft.EntityFrameworkCore;
using osu.Framework.Platform;
namespace osu.Game.Database
{
public abstract class DatabaseBackedStore
{
protected readonly Storage Storage;
protected readonly IDatabaseContextFactory ContextFactory;
/// <summary>
2017-10-25 21:07:32 +08:00
/// Refresh an instance potentially from a different thread with a local context-tracked instance.
/// </summary>
2017-10-25 21:19:47 +08:00
/// <param name="obj">The object to use as a reference when negotiating a local instance.</param>
/// <param name="lookupSource">An optional lookup source which will be used to query and populate a freshly retrieved replacement. If not provided, the refreshed object will still be returned but will not have any includes.</param>
/// <typeparam name="T">A valid EF-stored type.</typeparam>
protected virtual void Refresh<T>(ref T obj, IQueryable<T> lookupSource = null) where T : class, IHasPrimaryKey
2017-10-25 21:07:32 +08:00
{
2018-02-12 16:55:11 +08:00
using (var usage = ContextFactory.GetForWrite())
{
2018-02-12 16:55:11 +08:00
var context = usage.Context;
if (context.Entry(obj).State != EntityState.Detached) return;
var id = obj.ID;
var foundObject = lookupSource?.SingleOrDefault(t => t.ID == id) ?? context.Find<T>(id);
if (foundObject != null)
obj = foundObject;
else
context.Add(obj);
}
2017-10-25 21:07:32 +08:00
}
protected DatabaseBackedStore(IDatabaseContextFactory contextFactory, Storage storage = null)
{
2018-02-12 16:55:11 +08:00
ContextFactory = contextFactory;
Storage = storage;
}
/// <summary>
/// Perform any common clean-up tasks. Should be run when idle, or whenever necessary.
/// </summary>
public virtual void Cleanup()
{
}
}
}