【发布时间】:2021-12-27 14:29:23
【问题描述】:
您好,我正在使用 LiteDB,
我有 2 种对象类型
public class Player
{
public Guid Id { get; set; }
public string PlayerName { get; set; }
public long SoundCardId { get; set; }
public string SoundCardName { get; set; }
public Guid PlayerId { get; set; }
public long? Volume { get; set; }
public long OutputChannel { get; set; }
public Guid HardwareId { get; set; }
public IList<Schedules> Schedules { get; set; }
}
public class Schedule
{
public Guid Id { get; set; }
public DateTime startDate { get; set; }
public DateTime endDate { get; set; }
public DateTime startTime { get; set; }
public DateTime endTime { get; set; }
public int PlayDays { get; set; }
public string ScheduleName { get; set; }
public int Volume { get; set; }
public bool hasPriority { get; set; }
public bool isActive { get; set; }
public bool shuffleEnabled { get; set; }
public bool HarmonicShuffleEnabled { get; set; }
public DateTime LastUpdateDate { get; set; }
}
当我尝试插入 PlayerModel 时,它会毫无问题地插入。 似乎时间表列表和插入的 1 个成员,当我检查时间表的 ID 时,它是我设置的。 但 schedule 的其他属性是 null 或默认值.. 插入带有映射对象的对象的正确方法是什么
string dbPath = Path.Combine(Application.StartupPath, "music.db");
// set id as bsonid
BsonMapper.Global.Entity<Schedule>().Id(oid => oid.Id);
//set id as bsonid and ref other table
BsonMapper.Global.Entity<Player>()
.Id(oid => oid.Id)
.DbRef(x => x.Schedules, "SchedulesTable");
using (var db = new LiteDatabase(dbPath))
{
//create if not exists
var p1 = db.GetCollection<Player>("PlayerTable");
var p2 = db.GetCollection<Schedule>("SchedulesTable");
var p = new Player
{
PlayerId = Guid.NewGuid(),
HardwareId = Guid.NewGuid(),
OutputChannel = 1,
PlayerName = "default player",
SoundCardId = -1,
SoundCardName = "Default sound card",
Volume = 100,
Id = Guid.NewGuid(),
Schedules = new List<Schedule>()
};
var col = db.GetCollection<Player>("PlayerTable");
var q = col.Query().Include(c => c.Schedules).ToList();
if (q.Count() == 0)
{
var sch = new Schedule
{
Id = Guid.NewGuid(),
startDate = DateTime.Now,
endDate = DateTime.Now.AddDays(2),
startTime = DateTime.Now.Add(new TimeSpan(0, 0, 1)),
endTime = DateTime.Now.Add(new TimeSpan(22, 0, 0)),
isActive = true,
HarmonicShuffleEnabled = true,
hasPriority = false,
LastUpdateDate = DateTime.Now,
PlayDays = 127,
ScheduleName = "test schedule",
shuffleEnabled = true,
Volume = 100
};
p.Schedules.Add(sch);
var r1 = col.Insert(p);
col.EnsureIndex(c => new { c.HardwareId, c.PlayerId }, true);
//lets check if insert success?
var q1 = col.Query().Include(c => c.Schedules).FirstOrDefault();
//yes its inserted without any problem
var q2 = q1.Schedules.FirstOrDefault();
//yes there is one record..
//and the Id is the same with sch.Id
// but the rest of the properties are null or empty
}
【问题讨论】:
-
顺便说一下,IList 或 List 的结果是一样的