I am trying to write a simple CRUD on C#.
I am having troubles defining the relationships between these entities:
public class Movie
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
public Director Director { get; set; }
}
public class Director
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Movie> DirectedMovies { get; set; }
}
How do I make it so that one director can have multiple movies and one movie can have one director?
The Movie
table has the DirectorId
column but I cannot find a way to add a director to the movie from the frontend side.
In MovieController
, I have this code:
public ActionResult performAddMovie(Movie movie)
{
try
{
ctx.Movies.Add(movie);
ctx.SaveChanges();
return RedirectToAction("Index", "Home");
}
catch(Exception ex)
{
ModelState.AddModelError("Messaggio", ex.Message);
}
return RedirectToAction("Index", "Home");
}
This lets me add a new movie to the database, but I don't know how to add a director too.
Thank you
CodePudding user response:
The Director
is just another property. Presumably, before you pass a particular Movie
object to performAddMovie
, you're setting the title of the Movie
.
If you've got the ID of Director
, you can do:
var director = ctx.Directors.FirstOrDefault(d => d.Id == directorId);
movie.Director = director;
return performAddMovie(movie);
CodePudding user response:
you have add DirectorId property in Movie class
CodePudding user response:
Check this following code
public class Movie
{
public int Id { get; set; }
public string Title { get; set; }
public int DirectorId { get; set; }
[ForeignKey("DirectorId")]
public Director Director { get; set; }
}
public class Director
{
public int DirectorId { get; set; }
public string Name { get; set; }
public ICollection<Movie> DirectedMovies { get; set; }
}