Empty razor page with Entity Model relationships AspNet Core

Are you experiencing strange behavior when using Entity Model with one to one relationship ?

It may be caused by infinite loops on Json serialization and can be solved by adding  [JsonIgnore] annotation on dependent property.

Remember to include

using Newtonsoft.Json;

Example:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;


namespace YourData
{
	public class Company
    {
        [Required]
        [Key]
        public int ID { get; set; }

        public Customer Customer { get; set; }
    }

	//dependent entity
    public class Customer
    {
        [Required]
        [Key, ForeignKey("id")]
        public int ID { get; set; }

        [JsonIgnore] //Solution
        public Company Company { get; set; }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *