嗨,我在用LiteDB,
我有两个对象类型
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时,它插入时没有任何问题。此外,似乎计划列表和一个成员插入,当我检查计划的Id,这是我设置的。但是时间表的其他属性是空值或默认值。插入对象及其映射对象的正确方法是什么?
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
}
发布于 2021-12-27 16:38:55
找到答案了..。首先将计划插入到db,然后将其添加到可播放表中。
//add this
p2.Insert(sch);
//before this
p.Schedules.Add(sch);
https://stackoverflow.com/questions/70496795
复制相似问题