Using ASP.NET Core 2.1 and Entity Framework Core 2.1 I have the following entities:
public class Category {
public Int32 Id { get; set; }
public String Name { get; set; }
}
public class Post {
public Int32 Id { get; set; }
public Int32 CategoryId { get; set; }
public String Title { get; set; }
public String Content { get; set; }
public virtual Category Category { get; set; }
}
For seeding Categories I have the following:
modelBuilder.Entity<Category>().HasData(
new { Id = 1, Name = "Reading" },
new { Id = 2, Name = "Travelling" }
);
However, for seeding posts I am getting the data from YML files:
var posts = _service.GetPostsFromYMLFiles(path);
modelBuilder.Entity<Post>().HasData(posts);
The posts
are taken from YML files and are the following:
new { CategoryName = "Reading", Title = "A", Content = "A Content" },
new { CategoryName = "Travelling", Title = "B", Content = "B Content" }
These YML files are created by a third party and I cannot change them.
To seed these posts I believe I need to:
- Get the correspondent Category Id for each CategoryName;
- Generate an ID for each post.
The step (2) seems easy but how can I accomplish step (1)?
Instead of seeding the categories in place, save them to a variable first:
Then, pass this to
HasData
:With that, you can now query this list in memory to get the relevant categories while mapping your YML data to your
Post
entities:CategoryId
is non-nullable, so you probably want to create a fallback for if a particular category named in your YML does not actually exist. You may even consider seeding the categories themselves from the post YML, to ensure that everything in there actually exists: