none
Entity Framework with WCF recursive association issue RRS feed

  • Question

  • Hi,

    I am facing a recursive association issue when using Entity Framework and WCF.

    The entity is designed like below:

       
        [DataContract]
        public partial class User
        {
            public User()
            {
                this.Followers = new List<User>();
            }
        
            [DataMember] 
            public System.Guid Id { get; set; }
            [DataMember] 
            public string FirstName { get; set; }
            [DataMember] 
            public string LastName { get; set; }
            [DataMember] 
            public string Alias { get; set; }
            [DataMember] 
            public string Email { get; set; }
            [DataMember] 
            public string LoginName { get; set; }
            [DataMember] 
            public string Pwd { get; set; }
        
            [DataMember] 
            public virtual IList<User> Followers { get; set; }
        }

    Here is the method defined in WCF service,

            public ResultWrapper<User> GetUserWithInfo(string userId)
            {
                return base.TryDo<User>((entities) =>
                    {
                        var user = entities.Users
                            .Include(
                                u => u.Followers
                            ).FirstOrDefault(w =>          w.Id.Equals(new Guid(userId)));
                        return user;
                    });
            }

    However, I got an error says "Object graph...contains cycles and ...". 

    I actually have two question:

    1. Regarding EF, is it possible to control the depth of return list? Which means I just want the "Followers" of my current user, but not the "currentUser.Followers.Followers..."

    2. Regarding WCF, I want my response returns in JSON format, so "IsReference = true" doesn't work. Any other solution can work out?

    Monday, April 21, 2014 2:54 AM

Answers

  • 1) This is more of a EF issue and not WCF.

    2) No one really directly uses the EF entities sending them from the WCF service to the client or the client sending them back to the service. One use Data Transfer Objects with all projects using the DTO(s) having a reference to a classlib project called Entities as an example of the name where the DTO(s) are kept.

    http://en.wikipedia.org/wiki/Data_transfer_object

    DTO(s) are an abstraction away from the EF and the model, which are datacontrcts.

    Monday, April 21, 2014 9:13 PM