有不同的方法可以实现这一点,它只取决于最适合您的模型的方法,这里有几个:
测试型号:
public class IdIntKeyModel : RealmObject
{
[Indexed]
public int ID { get; set; }
public string Humanized { get; set; }
}
无间隙键排序(通过Count
):
注意:适用于初始批量导入
注意:假设只有一个线程添加记录,并且您的记录 ID 没有间隙,即没有重新排序键的删除等...
var config = RealmConfiguration.DefaultConfiguration;
config.SchemaVersion = 1;
using (var theRealm = Realm.GetInstance("StackoverFlow.realm"))
{
var key = theRealm.All<IdIntKeyModel>();
theRealm.Write(() =>
{
for (int i = 1; i < 1000; i++)
{
var model = theRealm.CreateObject<IdIntKeyModel>();
model.ID = key.Count() + 1;
model.Humanized = model.ID.ToWords();
System.Diagnostics.Debug.WriteLine($"{model.ID} : {model.Humanized}");
}
});
var whatIsTheKey = theRealm.All<IdIntKeyModel>().OrderBy(modelKey => modelKey.ID).Last();
System.Diagnostics.Debug.WriteLine($"{whatIsTheKey.ID} : {whatIsTheKey.Humanized}");
}
Gap'ie 键排序(通过 indexed 重新获取最后一条记录ID
):
注意:“Gap'ie”正在申请商标 ;-)
var rand = new Random();
var config = RealmConfiguration.DefaultConfiguration;
config.SchemaVersion = 1;
using (var theRealm = Realm.GetInstance("StackOverflow.realm"))
{
theRealm.Write(() =>
{
for (int i = 1; i < 1000; i++)
{
var lastID = theRealm.All<IdIntKeyModel>().OrderByDescending(modelKey => modelKey.ID).FirstOrDefault();
var model = theRealm.CreateObject<IdIntKeyModel>();
model.ID = lastID != null ? lastID.ID + rand.Next(10) : 1; // use lastID.ID++ for normal code flow, using rand.Next as a test to check ID indexing
model.Humanized = model.ID.ToWords();
}
});
var lastKey = theRealm.All<IdIntKeyModel>().OrderBy(modelKey => modelKey.ID).Last();
System.Diagnostics.Debug.WriteLine($"{lastKey.ID} : {lastKey.Humanized}");
}
注意:基于添加的支持的代码更新FirstOrDefault
,测试 w/v0.78.1