F#中的实体框架和匿名类型 [英] Entity Framework and Anonymous Types in F#
问题描述
尝试使用匿名类型获取查询:
Trying to get a query with an anonymous type working:
let temporaryBookModel =
query <@ context.Books
|> Seq.filter (fun book -> book.Id = bookId)
|> Seq.map(fun item -> (item.Id, item.ParentUser.Id, item.ParentUser.Alias, item.Tagline, item.Title, item.Visible, item.CreatedDate))
|> Seq.head @>
我不断得到:
{
LINQ to Entities中只支持无参数的构造函数和初始值设置。}
{"Only parameterless constructors and initializers are supported in LINQ to Entities."}
其中如果我将值直接映射到一个类型,那么匿名类型不应该抛出这个异常,因为它们是基于对象初始化器的功能的?不幸的是,我在匿名类型上找到的东西似乎说这是正确的语法。这样或这样的东西:
Which would make sense if I were mapping the values to a type directly, but anonymous types shouldn't throw this exception I would think since they are based on the object initializer functionality? Unfortunately anything I found on anonymous types seem to say this is the correct syntax. That or something like this:
let temporaryBookModel =
query <@ context.Books
|> Seq.filter (fun book -> book.Id = bookId)
|> Seq.map(fun item -> (("a", item.Id), ("b", item.ParentUser.Id), ("c", item.ParentUser.Alias), ("d", item.Tagline), ("e", item.Title, item.Visible), ("f", item.CreatedDate)))
|> Seq.head @>
推荐答案
F#是否支持匿名类型? strong>
Does F# supports anonymous types?
我知道 - 它没有。但是有两种可能的解决办法:
As I know - it doesn't. But there are 2 possible ways for workarounds:
- 使用元组(正如你所使用的)
- 使用记录类型,但在这种情况下,您需要先定义记录。这样的事情:
type Book =
{
Id: int;
ParentId: int;
ParentAlias: string;
TagLine: string;
Title: string;
Visible: bool;
CreatedDate: DateTime;
}
使用代码行将如下所示:
And usage code line will looks like:
...
|> Seq.map
(fun item ->
{
Id = item.Id;
ParentId = item.ParentUser.Id;
ParentAlias = item.ParentUser.Alias;
TagLine = item.Tagline;
Title = item.Title;
Visible = item.Visible;
CreatedDate = item.CreatedDate
})
您可以在类似的问题中找到更多的解释 here
More explanations you can find in similar question here
更新:
对于我来说,记录类型的使用是更优雅的解决方案,但是看起来它并不适用于Entity Framework - F# - >使用无参数构造函数进行记录?
Record types usage as for me is more elegant solution, BUT it looks like it doesn't not work with Entity Framework - F# -> Record with parameterless constructor?.
根据Tomas Petricek的回答,它必须被声明为具有较少构造函数和必要属性的参数的显式类型。
So according to Tomas Petricek answer - it has to be declared explicit type with parameters less constructor and necessary properties.
这篇关于F#中的实体框架和匿名类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!