我如何获得选项< t>来自实体框架核心数据库调用?
抱歉,如果这是一个愚蠢的问题,但是我正在与
在非功能代码中,我可以做类似的事情...
async Task DoFerretStuff(string id) {
Ferret? ferret = await ctx.Ferrets.FirstOrDefaultAsync(f => f.id == id);
if (ferret == null) {
// Do whatever needs doing when we can't find the ferret
} else {
// Do ferret stuff
}
}
我正在尝试以一种更有功能的方式执行此操作,并假设我能够做类似的事情...
async Task<Unit> DoFerretStuff(string id) =>
new Option<Ferret>(await ctx.Ferrets.FirstOrDefaultAsync(f => f.Id == id))
.Match(ferret => {
// Do ferret stuff
return unit;
},
() => {
// Do whatever needs doing when we can't find the ferret
return unit;
});
但是,这给了编译器错误第一行...
不能从“雪貂”转换为'system.collections.generic.enumerable'
我不明白为什么,因为我认为您可以将(可能为null)对象传递到构造函数中的 option&lt; t&gt; t&gt;
,它将给出某些&lt; t&gt;
或 none&lt; t&gt;
。
请有人可以解释我应该如何以功能性的方式做这种事情。
谢谢
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
The
Option
constructor尝试 pRELUDE.optional 函数而不是。这些过载中的一个具有无效的值,并将其转换为
option&lt; a&gt;
。话虽如此,如果您想立即
匹配
之后执行另一个副作用,那么与/else 相比,您将获得什么?FP通常涉及传递不变的值(例如
option&lt; ferret&gt;
)到纯函数。该值可以来自不纯的操作,例如ctx.ferrets.firstordefaultasync
,但它也可能只是当场创建的值。纯粹的功能不会在乎。The
Option
constructor takes anIEnumerable<A>
as argument, which explains the compiler error.Try the static
Prelude.Optional
function instead. One of those overloads takes a nullable value and converts it toOption<A>
.All that said, if you want to immediately
Match
on it afterwards to perform another side effect, then what are you gaining, compared toif/else
?FP would typically involve passing an immutable value (such as
Option<Ferret>
) to a pure function. The value can come from an impure action, such asctx.Ferrets.FirstOrDefaultAsync
, but it could also just be a value created on the spot. A pure function wouldn't care.