FSharp Record Types With Entity Framework Code-Fir

2020-06-19 22:00发布

I am doing a proof of concept in a line of business application where I want to swap out the current C# Code-First Entity Framework implementation with a F# one. I am following this article which seems to work pretty well, but I was hoping to use FSharp record types instead of the classes that the article uses. When I try and add a data annotation to a record type like this:

type Family = {[<Key>]Id:int; LastName:string; IsRegistered:bool}

I get the following error:

Error   1   The type 'Key' is not defined

Is there a way to use data annotations with record types? Apparently, EF Code-First needs annotations...

1条回答
家丑人穷心不美
2楼-- · 2020-06-19 22:36

Record types support attributes just fine (and with the syntax you have).

Check if your reference to System.ComponentModel.DataAnnotations is in order, that's where KeyAttribute is defined.

Edit: EF wants to work with properties, that's why using a record doesn't mesh well with EF. You can still make it work in F# 3.0+ by marking the record with CLIMutable attribute (this generates property setters and a parameterless constructor which are taken for granted by C#-centric frameworks and libraries).

The article you're looking at was written with F# 2.0 in mind - CLIMutable wasn't around yet and there was no way of using records for that.

查看更多
登录 后发表回答