Entity Framework navigation property

2019-08-02 02:25发布

问题:

I'm trying to use EF to get data from my database. I have a table Interventions that has a Client associated with it like this:

public partial class Client
{
    public Client()
    {
        this.Interventions = new List<Intervention>();
    }

    public int client_id { get; set; }
    public string full_name { get; set; }
    public string cgroup { get; set; }
    public string nation { get; set; }
    public virtual ICollection<Intervention> Interventions { get; set; }
}

public partial class Intervention
{
    public int intervention_id { get; set; }
    public int technician_id { get; set; }
    public int client_id { get; set; }
    public string type { get; set; }
    public int done { get; set; }
    public int year { get; set; }
    public int month { get; set; }
    public int week { get; set; }
    public Nullable<int> avg_response_time { get; set; }
    public int number_of_equip { get; set; }
    public virtual Client Client { get; set; }
    public virtual Technician Technician { get; set; }
}

I can get a list of interventions by doing this:

public object Any(GetInterventions request)
    {
        List<Intervention> dbItems;
        using (var context = new operationsContext())
        {
            context.Configuration.LazyLoadingEnabled = false;
            dbItems = context.Interventions.ToList();
            return new GetInterventionsResponse{
                interventions = dbItems
            };
        }
    }

Although, when I try to retrieve the client associated with each intervention

dbItems = context.Interventions.Include("Client").ToList();

by including a Client navigation property I get a Visual Studio a stackOverflowException. Am I doing anything wrong using EF or is just a question of general bad programming?

thanks in advance

回答1:

The problem was solved by introducing decorations of [DataContract] and [DataMember] on the classes and fields that I wanted to serialize on the JSON response. Just like the example below:

using System.Runtime.Serialization;
namespace OperationsAPI.Models
{
    [DataContract]
    public partial class Intervention
    {
        public int intervention_id { get; set; }
        public int technician_id { get; set; }
        public int client_id { get; set; }
        public string type { get; set; }
        public int done { get; set; }
        public int year { get; set; }
        [DataMember]
        public int month { get; set; }
        [DataMember]
        public int week { get; set; }
        [DataMember]
        public Nullable<int> avg_response_time { get; set; }
        public int number_of_equip { get; set; }
        [DataMember]
        public virtual Client Client { get; set; }
        public virtual Technician Technician { get; set; }
    }
}