У меня есть 2 модели классов mov ie и покупатель. Я сделал внешний ключ один ко многим, чтобы я мог добавить mov ie в список клиентов. Но теперь я не могу добавить mov ie к клиенту и не получаю никаких ошибок.
Вот мой код.
Mov ie 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; }
}
Класс клиента
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>();
}
И вот код в моем классе CustomerController
, который должен добавить mov ie моему клиенту
[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");
}
Я надеюсь кто-то может сказать мне, что не так с моим кодом.