I'm trying to build a web app (ASP.NET MVC3) that uses Entity Framework, and I've once again hit a wall. It throws following exception when trying to run a foreach loop over the collection in the view:
System.InvalidOperationException: The
class 'GvG.Entities.News' has no
parameterless constructor.
Now is my question, is it possible to somehow define a parameterless constructor on my record type?
My record type at the moment looks like:
type News = {
mutable ID:int;
mutable Author:string;
mutable Title:string;
mutable Content:string }
I'm aware of that I can create a class with baking-fields etc. instead, but thats what I'm trying to avoid.
I tried to solve this (espeically for Entity Framework) during some contracting project I did for the F# team and you can find an experimental solution in F# PowerPack sources. It is not fully tested & you'd have to build it yourself. The experimental solution replaces all F# tuples and F# records in the query with other (mutable) types and then transforms results back to records/tuples.
EDIT Didn't see the mention about defining class in your question, but I'll leave the example here for others who may come here with the same issue.
There is no easy workaround. The unfortunate solution is to define a class with properties explicitly:
type News() =
let mutable id = 0
let mutable author = ""
let mutable title = ""
let mutable content = ""
member x.ID with get() = id and set(v) = id <- v
member x.Author with get() = author and set(v) = author <- v
member x.Title with get() = title and set(v) = title <- v
member x.Content with get() = content and set(v) = content <- v
That's very ugly compared to records, but it's the only way to do it in the current version of F#. It is something that the F# team is aware of, so there may be some better solution in the next version.
It's an old one, but I stumbled upon similar issue today, and looks like with F# 3.0 you can overcome it with [<CLIMutable>]
attribute: http://msdn.microsoft.com/en-us/library/hh289724.aspx
This way you can use your F# immutable records in many scenarios when C# API requires POCO.
MSDN says "In a record type, you cannot define a constructor."
http://msdn.microsoft.com/en-us/library/dd233184.aspx