首页 文章

MongoDB C#选择特定列

提问于
浏览
1

我知道MongoDb C#驱动程序不支持投影,所以我搜索了一下,我发现很多人使用mongoCursor来执行这样的查询,我试图只选择特定的字段,我的代码如下:

public T GetSingle<T>(Expression<Func<T, bool>> criteria,params Expression<Func<T, object>>[] fields) where T : class
{
    Collection = GetCollection<T>();
    return Collection.FindAs<T>(Query<T>.Where(criteria)).SetFields(Fields<T>.Include(fields)).SetLimit(1).SingleOrDefault();
}

我得到了用户的自定义存储库:

public User GetByEmail(string mail, params Expression<Func<User, object>>[] fields)
{
    return GetSingle<User>(x=>x.Email==mail,fields);
}

这是用法:

_repository.GetByEmail(email, x=>x.Id,x=>x.DisplayName,x=>x.ProfilePicture)

但我得到参数中包含的字段,以及作为类User的一部分的所有枚举,日期和布尔值,字符串中未包含在字段列表中的值为空,这样就可以了

enter image description here

what can I do to avoid that?

1 回答

  • 2

    通过使用 SetFields ,您可以指定通过电线的内容 . 但是,在这种情况下,您仍然要求驾驶员返回 TUser 类型的水合物体 .

    现在,类似于 intenumbooleanvalue types,所以它们的值不能是 null . 所以这严格来说是一个C#-problem:这些属性根本没有值表明它们不存在 . 相反,它们采用默认值(例如 boolbool ,_1767625为数字类型) . 另一方面, stringreference type所以它可以为null .

    策略

    Make the properties nullable 您可以在模型中使用可空字段,例如:

    class User {
        public bool? GetMailNotifications { get; set; }
    }
    

    这样,值类型可以具有其有效值之一或 null . 但是,这可能会使用起来很笨拙,因为每当您想要访问该属性时,您都必须进行 null 检查并使用 myUser.GetMailNotifications.ValuemyUser.GetMailNotifications.GetValueOrDefault 帮助程序 .

    Simply include the fields instead 这没有回答如何做到的问题,但至少有三个充分理由说明为什么包含它们是个好主意:

    • 当传递 User 对象时,它有意义,因为对象不完整

    • 它更容易使用

    • 性能优势可以忽略不计,除非你这里的情况如此 .

    所以问题是:你为什么要尽一切努力排除某些领域?

相关问题