Giordano bruno
Giordano bruno

Reputation: 1

Entity Framework 6 entity mapping

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

Upvotes: 0

Views: 48

Answers (3)

Mehdi Kacim
Mehdi Kacim

Reputation: 152

Check this following code

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; }
}

Upvotes: 0

Quasipickle
Quasipickle

Reputation: 4498

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);

Upvotes: 1

KHYT
KHYT

Reputation: 1

you have add DirectorId property in Movie class

Upvotes: 0

Related Questions