I have 2 model classes movie and customer. I made a one to many foreign key so that I can add a movie to a list in customer. But now I am unable to add a movie to a customer and I don't get any errors either.
Here is my code.
Movie class
public class Movie
{
[Key]
public int MovieId { get; set; }
public String Name { get; set; }
[Column(TypeName = "datetime2")]
public DateTime? DateCreated { get; set; }
public int? CustomerId { get; set; }
public Customer Customer { get; set; }
}
Customer class
public class Customer
{
[Key]
public int CustomerId { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public bool IsCreated { get; set; }
public int MaxMovies { get; set; }
[Column(TypeName = "datetime2")]
public DateTime Created { get; set; }
[Column(TypeName = "datetime2")]
public DateTime? LastEdited { get; set; }
[ForeignKey("MovieId")]
public List<Movie> Movies = new List<Movie>();
}
And here is the code in my CustomerController
class that should add the movie to my customer
[HttpGet]
public IActionResult AddMovie(int id)
{
List<Movie> movieList = new List<Movie>();
movieList = dbContext.Movies.ToList();
AddMovieViewModel viewModel = new AddMovieViewModel()
{
movies = movieList,
customer = dbContext.Customers
.Where(s => s.CustomerId == id)
.FirstOrDefault()
};
return View(viewModel);
}
[HttpPost]
public IActionResult AddMovie (int id,int cid)
{
Customer customer = dbContext.Customers
.Where(s => s.CustomerId == cid)
.FirstOrDefault();
Movie movie = dbContext.Movies
.Where(s => s.MovieId == id)
.FirstOrDefault();
movie.CustomerId = customer.CustomerId;
customer.Movies.Add(movie);
dbContext.SaveChanges();
return RedirectToAction("Index");
}
I hope someone can tell me whats wrong with my code.