如何使用 Realm for Xamarin 实现 "get or create" 查询?

How to implement "get or create" query with Realm for Xamarin?

考虑简单模型:

public class Session : RealmObject
{
    [ObjectId]
    public string UserId { get; set; }
    public string Token { get; set; }
}

如何通过 ID 获取 Session 实例或 null 如果它不存在?

var realm = Realm.GetInstance ();
var q = realm.All<Session> ().Where ((x) => x.UserId = "1");
// This won't work if no session is saved:
// var session = q.First ();
// and this won't either
// var session = q.FirstOrDefault ();
// And this is mmm... kind of strange but it's working :)
var session = q.Count() > 0 ? q.First() : null;

那么,设计应该如何完成?

喜欢做的是:

var localSession = theRealm.All<Session>().FirstOrDefault((Session session) => session.UserId == "1");

但是FirstOrDefault/SingleOrDefault不支持(截至0.77.2

当前支持

AnyFirstSingle (Current Linq Support):

If/Else Any 风格:

Session session = null;
var sessions = theRealm.All<Session>().Where((Session localSession) => localSession.UserId == "1");
if (!sessions.Any())
    theRealm.Write(() =>
    {
        session = new Session() { UserId = "1", Token = "SO" };
    });
else
    session = sessions.First();
D.WriteLine($"{session?.UserId}:{session?.Token}");

Try/Catch 在 InvalidOperationException:

Session localSession = null;
try
{
    localSession = theRealm.All<Session>().First((Session session) => session.UserId == "1");
}
catch (InvalidOperationException error) when (error.Message == "Sequence contains no matching element")
{
    theRealm.Write(() =>
    {
        localSession = new Session() { UserId = "1", Token = "SO" };
    });
}
D.WriteLine($"{localSession?.UserId}:{localSession?.Token}");

更新var localSession = theRealm.All<Session>().FirstOrDefault(session => session.UserId == "1"); 的支持已从 0.78.0 版本开始提供。

原创

我现在正在研究相关的Realm issue

请在此处添加您希望支持的特定场景的评论。

请注意,如果您想在正式 NuGet 发布之前尝试一些东西,我们现在也有 Nightly feed