I'm trying to translate the example Entity Framework Core to F# but I can't translate the BloggingContext
class.
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
.
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!
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;"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With