简体   繁体   中英

LiteDb auto-increment id sub list of class

I have these classes and got issue with auto increase id of sub lists:

class A
{
    public int Id { get; set; }
    public string Value { get; set; }
    public List<B> Bs { get; set; }
}

class B
{
    public int Id { get; set; }
    public string Value { get; set; }
    public List<C> Cs { get; set; }
}

class C
{
    public int Id { get; set; }
    public string Value { get; set; }
}

How can I automatically increase the id of the B and C? I can add values but id inside the sub list they're always 0.

In general, an A item can contain B with the same id, as well as different B items can contain C with the same id.

If you just need different ids, you can assign them right in the code just like other properties.

If it is required to support consistency and assign a new id to every sub-item, the items should be stored in separate collections:

var collectionA = db.GetCollection<A>("a");
var collectionB = db.GetCollection<B>("b");
var collectionC = db.GetCollection<C>("c");

BsonMapper.Global.Entity<A>().DbRef(x => x.Bs, "b");
BsonMapper.Global.Entity<B>().DbRef(x => x.Cs, "c");

foreach (var c in a.Bs.SelectMany(x => x.Cs).Where(x => x.Id == 0))
    collectionC.Insert(c);
foreach (var b in a.Bs.Where(x => x.Id == 0))
    collectionB.Insert(b);
collectionA.Insert(a);

More details about sub-documents are available in the documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM