我试图在我的Xamarin项目中从SQLite更改为Realm.io,但无法在ID上找到任何自动增量。我发现了一篇带有Java的帖子,其中包含以下行:
int nextID = (int) (realm.where(dbObj.class).maximumInt("id") + 1);
在Xamarin中没有地方,但我试过这个:
realm.All<DebitorPlateDBModel> ().Max (x => x.Id + 1);
悲伤地&#34; Max&#34;不支持。
有没有人成功呢?
答案 0 :(得分:2)
实现这一目标的方法有很多种,它取决于最适合您模型的方式,这里只是一对:
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}");
}
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
答案 1 :(得分:0)
“在Xamarin中没有”不正确 - 我们支持LINQ,您可以在home page的片段中看到。
但是,是正确,我们还没有(还)有自动增量或该角色的任何内容。
我们会在某些时候获得某些内容,但由于同步问题,它不会是auto-increment
,而是auto-unique-id
之类的内容。
我们刚刚发布了带有同步的完整Mobile Platform(Xamarin即将到达)。 Realm Object Server的一项重大交易是处理正在编辑离线数据然后与其他Realms进行高度可靠同步的人。
无法使用简单的自动增量来处理断开连接的数据创建(我第一次处理这个问题是在1996年的Mac上,但是物理定律没有改变,我们只是停止使用软盘)。
答案 2 :(得分:0)
Realm实际支持where子句。您只需要导入linq。但是,自动增量ID确实很重要。
我通过创建自己的ID来解决自动增量问题
using Realms;
using System;
namespace RealmDatabase
{
public class RealmUserObject : RealmObject
{
[PrimaryKey]
public int userID { get; set; }
public string userLoginName { get; set; }
public DateTimeOffset userCreated { get; set; }
public bool userActive { get; set; }
}
}
然后在添加帐户时,我从领域获取最后一个用户信息,然后从中获取最后一个ID(即int),然后在插入新帐户之前获得+ 1.
public List<RealmUserObject> getAllUserAccountsFromDatabase()
{
try
{
realm = Realm.GetInstance(config);
return realm.All<RealmUserObject>().Last();
}
catch (Exception) { throw; }
}
我正在调用整个帐户,因为它在其他情况下对我有用。但你实际上可以这样直接问你想要什么
return realm.All<RealmUserObject>().Last().userID;
注意:当然,如果您没有任何记录存在,那么只需插入它并将id初始化为1并在帐户大于0时放入其他