1

I have simple controller:

   public IEnumerable<Company> GetAll() {
       using (SomeEntities data = new SomeEntities()) {
          return data.Companies.ToList<Company>();
       }
    }

And Company class from ADO.NET Entity model:

namespace Some.Models {
    using System;
    using System.Collections.Generic;

    public partial class Company {
        public Company() {
            this.Employees = new HashSet<Employee>();
        }

        public int COMP_ID { get; set; }
        public string COMP_NAME { get; set; }

        public virtual ICollection<Employee> Employees { get; set; }
    }
}

My problem is that the controller returns JSON with all companies with all employees.

I just want to get list of Companies (like in DB - employees have FK to Companies, not the other way around). I don't want them in list of Companies.

I tried to set getter of Employees in Company model to protected, which works, but then I can't access Emplyees in C# code so I need to create new method in Company model:

public ICollection<Employee>  GetEmployees() {
    return Employees;
}

And after every Update Model From Database my code is purged and I need to write it again.

This solution doesn't seem proper. What is the proper way to achieve this? Thanks

Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
  • Instead of serializing your model, why not use a DTO that contains only the properties you want to serialize? – Brian Rogers Oct 20 '15 at 23:24
  • You mean like creating a view in DB or new Company class - wouldn't that be a performace costly to everytime convert ADO.NET Company class to some mine for every row? Could you give an example please? – Šimon Hlaváč Oct 21 '15 at 07:19
  • Not a view in the DB, [a separate object](http://stackoverflow.com/questions/1051182/what-is-data-transfer-object) that has the only properties you want to serialize. Like if your model is called `Company`, your DTO would be called `CompanyDTO`. You can use something like [Automapper](http://automapper.org/) to copy the properties from one object to the other. – Brian Rogers Oct 21 '15 at 14:25

0 Answers0