I'm migrating a project from EF core 2 to EF 7 when i found that in EF 7 after scaffolding, context models no longer have setters on virtual collection, example:
public class Blog
{
public int Id { get; set; }
public string Name { get; set; }
public string Author { get; set; }
public ICollection<Post> Posts { get; } = new List<Post>();
}
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public DateTime PostedOn { get; set; }
public Blog Blog { get; set; }
}
when inserting a new blog, I used to do it this way:
var blog = new Blog()
{
Name = "",
Author = "",
Posts = new List<Post>() {
new Post(){Title="", Content = "" },
new Post(){Title="", Contect = "" },
new Post(){Title="", Contect = "" },
}
};
_context.RetailLot.Add(blog);
_context.SaveChanges();
Apparently I cant do this anymore since it doesn't have a setter and my 2 options would be to add init keyword replacing the setter or keep it without a setter but manually add the posts by using someething like this
var blog = new Blog()
{
Name = "",
Author = ""
}
blog.Posts.Add(new Post(){Title="", Content = "" });
blog.Posts.Add(new Post(){Title="", Content = "" });
blog.Posts.Add(new Post(){Title="", Content = "" });
Are these indeed the only ways cause the second seems very manual and with adding init than force-scaffolding would replace it without using T4 templates...
Also I came across many instances where we fetch from context and we customize the select statement like below
_context.Blogs.include(x=>x.Posts).Select( b => new Blog(){
Name = "MyBlog_"+x.Name,
Author = x.Author,
Posts = x.Posts
});
this is a simple example to how I needed to manipulate the returned object by selecting some specific columns to be returned or customize some columns. Posts=x.Posts will error out here because its a readonly. is adding init keyword my only acceptable option ? other workarounds is to create a new model that extend Blog but also override it to include a setter..