I want to separate the Genre from Movie in my database.
I must have two tables: Movie and Genre. They must be linked by the Foreign Key GenreID in the Movie table.
As the above tutorial doesn't show me how to do it. I would like to get your help here.
How do I generate the database properly from my models?
PS: I already created two Models classes: Movie and Genre.
After scaffolding, only one table was generated in the database: Movie.
From the MS document, it seem that the Movie and Genre has the one to many relationships, in this scenario, when create the model, you can use the following code:
//using System.ComponentModel.DataAnnotations;
//using System.ComponentModel.DataAnnotations.Schema;
public class Movie
{
public int Id { get; set; }
public string? Title { get; set; }
[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }
public decimal Price { get; set; }
[ForeignKey("Genre")]
public int GenreId { get; set; }
public Genre Genre { get; set; }
}
public class Genre
{
public int GenreId { get; set; }
public string Title { get; set; }
public List<Movie> Movies { get; set; }
}
Then, in the MvcMovieContext, add the following code:
public class MvcMovieContext : DbContext
{
public DbSet<Movie> Movies { get; set; }
public DbSet<Genre> Genres { get; set; }
public MvcMovieContext(DbContextOptions<MvcMovieContext > options)
: base(options)
{
}
}
After that, use the following commands to enable migration in the Package Manager Console:
Add-Migration AddMovies
Update-Database
Then, you can see it already create the Movie and Genre tables in the database.
Check the following screenshot.
[Note] When insert the related entities to the database, please pay attention to the new item. It is better to check whether the related entities exist in the database, then based on the result to use the exist item or create the new item.
Code like this:
Here are some related articles about EF core relationship, you can refer to them:
One-to-Many Relationship Conventions in Entity Framework Core
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion