Entity framework - Avoid circular relationships in serialization

I have two tables: Users and Profiles . The user has one profile (1: 1), the profile can be affected by many users, each profile has many modules, each module has many actions.

I am sending this object from asmx to an aspx page using a direct service call.

I got an error due to lazy loading ... so I turned off lazy loading.

 this.Configuration.LazyLoadingEnabled = false; 

this works fine, I got my user with a zero profile.

To build a menu tree, I need to get a profile. I turned it on:

  User user = new User(); using (cduContext db = new cduContext()) { // get the user string encryptedPassword = Encryption.Encrypt(password); user = (from u in db.Users where u.UserName.Equals(login) && u.Password.Equals(encryptedPassword) select u).FirstOrDefault(); // Include the users profile user = db.Users.Include("Profile").FirstOrDefault(); } return user; 

I got this error in javascript call function:

A loopback link was found while serializing an object of type "CDU.Entities.Models.User".

When I quickly looked at the user object in asmx (before sending it), I found that the profile included a list of users who had this pofile, each user uploaded his profile ... etc.

Any idea please?

+4
source share
1 answer

Please note: your code should look like this:

 using (cduContext db = new cduContext()) { // get the user string encryptedPassword = Encryption.Encrypt(password); var user = from u in db.Users where u.UserName.Equals(login) && u.Password.Equals(encryptedPassword) select u; // Include the users profile return user.Include("Profile").FirstOrDefault(); } 

In your code, you threw out the first request, overwriting it with the second. And there was no reason to create an empty user.

To solve your problem, you must decide what you do not want to serialize. In your case, you probably don't want to serialize Profile.Users

You do not mention which serializer you are using. I assume you are using a DataContract serializer?

EDIT:

Mark your Profile.Users object with the [IgnoreDataMember] attribute.

+3
source

Source: https://habr.com/ru/post/1469317/


All Articles