如何使用Realm for Xamarin实现“获取或创建”查询?

时间:2016-08-31 15:46:00

标签: c# xamarin realm realm-net

考虑简单模型:

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;

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

2 个答案:

答案 0 :(得分:2)

What you would like to do is:

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

But FirstOrDefault/SingleOrDefault is not yet supported (as of 0.77.2)

Any, First and Single are currently supported (Current Linq Support):

If/Else on Any style:

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

答案 1 :(得分:2)

<强>更新var localSession = theRealm.All<Session>().FirstOrDefault(session => session.UserId == "1");的支持已在0.78.0版本中发布。

<强>原始

我现在正在处理相关的Realm issue

请为您支持的具体方案添加评论。

请注意,如果您想在官方NuGet发布之前尝试一些事情,我们现在还有一个Nightly feed