0

考虑简单的模型:

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

如何Session通过 ID 获取实例或者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;

那么,它应该如何通过设计来完成呢?

4

2 回答 2

2

想做的是:

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

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

AnyFirst并且Single当前受支持(Current Linq Support):

If/ElseAny风格:

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}");

尝试/赶上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}");
于 2016-08-31T16:55:08.803 回答
2

更新 支持var localSession = theRealm.All<Session>().FirstOrDefault(session => session.UserId == "1");已在 0.78.0 版以后提供。

原来的

我现在正在处理相关的Realm 问题

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

Note that we also now have a Nightly feed if you want to try something ahead of an official NuGet release.

于 2016-09-01T09:23:12.433 回答