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 @>
And I keep getting:
{"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 @>
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
})
More explanations you can find in similar question here
Update:
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?.
So according to Tomas Petricek answer - it has to be declared explicit type with parameters less constructor and necessary properties.