Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translate Entity Framework Core Example to F#

I'm trying to translate the example Entity Framework Core to F# but I can't translate the BloggingContextclass.

Until now I wrote

type BloggingContext() =
inherit DbContext()

member val Blogs = DbSet<Blog>() with get,set
member val Posts = DbSet<Post>() with get,set

which is incomplete and Visual Studio Code complains that DbSet has no accessible object constructors. Besides that, I don't know how to override the method OnConfiguring.

like image 898
Vitor Avatar asked Jan 04 '23 05:01

Vitor


2 Answers

I used the Fyodor's answer but later when I try to add a new Blog to the set I receive a null reference exception. So, the answer I found is to modify the declarations of Blogs and Posts to be:

[<DefaultValue>] val mutable m_blogs : DbSet<Blog>
    member public this.Blogs with get() = this.m_blogs 
                                        and set v = this.m_blogs <- v

[<DefaultValue>] val mutable m_posts : DbSet<Post>
    member public this.Posts with get() = this.m_posts 
                                        and set v = this.m_posts <- v

The override keyword solution worked fine for me!

like image 129
Vitor Avatar answered Jan 06 '23 17:01

Vitor


Since DbSet<T> has no public constructors, you can't create instances of it yourself. The idea was that you would just declare properties with null as initial value, and EF will assign new values to them later. So you can just specify the initial value of null, that should do it:

member val Blogs: DbSet<Blog> = null with get,set

To override a method, use the override keyword:

override this.OnConfiguring optionsBuilder =
   optionsBuilder.UseSqlServer @"Server=(localdb)\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;"
like image 23
Fyodor Soikin Avatar answered Jan 06 '23 17:01

Fyodor Soikin