1

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 Answers 2

6

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;
Sign up to request clarification or add additional context in comments.

3 Comments

I've added these two lines to my DbContext constructor this.Configuration.ProxyCreationEnabled = false; this.Configuration.LazyLoadingEnabled = false; But i get same error
can you check in you debuggers, look into the object to be return and make sure that the object proxy is not create
It wasn't that, somehow I solved problem by deleting a database and creating it again :/
0

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 ???

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.