-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathLocoDb.cs
More file actions
60 lines (50 loc) · 2.37 KB
/
LocoDb.cs
File metadata and controls
60 lines (50 loc) · 2.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using Microsoft.EntityFrameworkCore;
using OpenLoco.Dat.Types;
namespace OpenLoco.Definitions.Database
{
public class LocoDb : DbContext
{
public DbSet<TblLocoObject> Objects => Set<TblLocoObject>();
public DbSet<TblAuthor> Authors => Set<TblAuthor>();
public DbSet<TblTag> Tags => Set<TblTag>();
public DbSet<TblModpack> Modpacks => Set<TblModpack>();
public DbSet<TblLicence> Licences => Set<TblLicence>();
public DbSet<TblUser> Users => Set<TblUser>();
public DbSet<TblRole> Roles => Set<TblRole>();
public LocoDb()
{ }
public LocoDb(DbContextOptions<LocoDb> options) : base(options)
{ }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
_ = optionsBuilder.UseSqlite("Data Source=Q:\\Games\\Locomotion\\Server\\loco-dev.db");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<TblLocoObject>()
.Property(x => x.UploadDate)
.HasDefaultValueSql("datetime(datetime('now', 'localtime'), 'utc')"); // this is necessary, it seems like a bug in sqlite
modelBuilder.Entity<TblUser>()
.Property(x => x.CreatedDate)
.HasDefaultValueSql("datetime(datetime('now', 'localtime'), 'utc')"); // this is necessary, it seems like a bug in sqlite
}
public bool DoesObjectExist(S5Header s5Header, out TblLocoObject? existingObject)
=> DoesObjectExist(s5Header.Name, s5Header.Checksum, out existingObject);
public bool DoesObjectExist(string originalName, uint originalChecksum, out TblLocoObject? existingObject)
{
// there's a unique constraint on the composite key index (OriginalName, OriginalChecksum), so check existence first so no exceptions
// this isn't necessary since we're already filtering in LINQ, but if we were adding to a non-empty database, this would be necessary
var existingEntityInDb = Objects
.FirstOrDefault(e => e.OriginalName == originalName && e.OriginalChecksum == originalChecksum);
var existingEntityInChangeTracker = ChangeTracker.Entries()
.Where(e => e.State == EntityState.Added && e.Entity.GetType() == typeof(TblLocoObject))
.Select(e => e.Entity as TblLocoObject)
.FirstOrDefault(e => e!.OriginalName == originalName && e.OriginalChecksum == originalChecksum);
existingObject = existingEntityInDb ?? existingEntityInChangeTracker;
return existingObject != null;
}
}
}