The ForeignKeyAttribute on property "[Model name]" on type "[Project name]" is not valid

asp.net-core asp.net-mvc c# entity-framework-core

Question

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.

1
1
2/17/2020 12:38:30 PM

Popular Answer

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; }
1
2/17/2020 1:46:40 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow