So i tried to add a foreign key by following this tutorial. But now im getting an error i have looked for an anwser but couldn't find any. these are my model classes
Movie class
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace MovieExampleAppDotNetCore.Models
{
[Table("Movie")]
public class Movie
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int MovieId { get; set; }
public string Name { get; set; }
[Column(TypeName = "datetime2")]
public DateTime? DateCreated { get; set; }
public int? CustomerId { get; set; }
[ForeignKey("Customer")]
public Customer customer { get; set; }
}
}
Customer class
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace MovieExampleAppDotNetCore.Models
{
[Table("Customer")]
public class Customer
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
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; }
public ICollection<Movie> BorrowingMovies { get; set; }
}
}
I hope someone can help me with my problem.
You must have property's name with pascal-case :
public Customer Customer { get; set; }
Also, there is no need to use data-annotation in this case.
Furthermore, the types of CustomerId
are different in Movie
and Customer
. It could not be nullable in Movie
. Your foreign key must be defined like this:
public int CustomerId { get; set; }