Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Record with parameterless constructor?

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.

like image 660
ebb Avatar asked Apr 02 '11 12:04

ebb


People also ask

How do you call a parameterless constructor?

A constructor that takes no parameters is called a parameterless constructor. Parameterless constructors are invoked whenever an object is instantiated by using the new operator and no arguments are provided to new .

Can record inherit class?

However, a record can't inherit from a class, and a class can't inherit from a record.

Can a record implement interface C#?

It's legal to implement an interface with a record.

Can we use constructor in structure in C#?

Features of C# StructuresStructures can have defined constructors, but not destructors. However, you cannot define a default constructor for a structure. The default constructor is automatically defined and cannot be changed. Unlike classes, structures cannot inherit other structures or classes.


1 Answers

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.

like image 130
Bartosz Avatar answered Oct 08 '22 21:10

Bartosz