1
votes

In Web Api project when I enter url localhost:[portnumber]/api/os, I get long XML file containing errors, here is Exception Message:

Type 'System.Data.Entity.DynamicProxies.CollegeCourse_C7F37B1980970AF17607E96F17DFE50E3A680141BF8228EEA7D39A9150498388' with data contract name 'CollegeCourse_C7F37B1980970AF17607E96F17DFE50E3A680141BF8228EEA7D39A9150498388:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.

But when I enter url localhost: [portnumber]/api/role everything is fine, here is code:

OS:

public class UserOS
{
    [Key]
    [HiddenInput(DisplayValue = false)]
    public int UserOSId { get; set; }

    public Guid UserId { get; set; }

    public string OSType { get; set; }

    [ForeignKey("UserId")]
    public virtual User User { get; set; }
}

Role:

public class UserRole
{
    [Key]
    [HiddenInput(DisplayValue = false)]
    public int RoleId { get; set; }

    public string Name { get; set; }

    public ICollection<User> Users { get; set; }

}

And API controller for Role and OS is similar, so I'll paste for Role only:

  private CompeteDataBase _competeDataBase = new CompeteDataBase();

   public IEnumerable<UserRole> GetAllRoles()
   {
       return _competeDataBase.UserRoles.AsEnumerable();
   }

Edit

Is it correct way to use DTOs ?

2

2 Answers

6
votes

This is because EntityFramework creates a 'proxy' of your class.

To make this work, simply disable the proxy creation. You can go into your Context constructor and add the following:

ContextOptions.ProxyCreationEnabled = false;
0
votes

Somehow I managed to solve problem, I don't know how or why but deleting database and crating in again solved everything (I didn't change anything else)

Does anyone maybe know why ???