1

I am new to WCF. I am trying to create List with LINQ result by using Entity Framework. I want to return JSON data. But i am not able to get it. I am getting error like Notsupportedexception was unhandled by user code. Please help me to solve this problem. Thanks in advance.

This is my Service Constructor:

[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "getcontact")]
List<string> JSONDataAll();

If i return like this its working fine:

public List<String> JSONDataAll()
{   
var users = (from u in db.Tbl_Users select u).ToList();
var finalList= users.Select(u => u.UserName).ToList();
return st;
}

In this case its showing error:

public List<String> JSONDataAll()
{
var users = (from u in db.Tbl_Users
select new
{ u.UserName,
u.UserAddress
}).ToList();
return users;
}
Vetri
  • 347
  • 2
  • 6
  • 23
  • I tried that one also. Its showing error like Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.List – Vetri Sep 18 '14 at 09:14
  • I didn't suggest to return anonymous type, since you return list of `Tbl_Users`, you can just do `var result = (from u in db.Tbl_Users select u);`, then you're golden – Yuliam Chandra Sep 18 '14 at 09:17
  • @Yuliam Chandra. Yeah i am getting it without any condition. But if i try to give some conditions in LINQ query its showing conversion error :( – Vetri Sep 18 '14 at 09:20
  • it's a different question then, your code doesn't show any filter condition, please update your code that uses `select u` with conditions – Yuliam Chandra Sep 18 '14 at 09:21
  • @ Yuliam Chandra. I have updated my code above. Please check it out – Vetri Sep 18 '14 at 09:42

1 Answers1

0

Since you are using WCF, to do a projection (select clause) you can create a new type as return type instead of anonymous object or a derived object and the EF entity can't be used to do a projection.

The derived object might cause the localhost.com issue per the discussion, probably there is an invalid proeprty value. And you can also take the benefits of configuring it with DataMember attribute.

[DataContract]
public class UserDataResponse
{
    [DataMember]
    public string UserName { get; set; }
    [DataMember]
    public string UserAddress { get; set; }
}

And change the return type of the WCF operation.

public List<UserDataResponse> JSONDataAll()
{
    var users = (from u in db.Tbl_Users
                select new UserDataResponse
                {
                    UserName = u.UserName,
                    UserAddress = u.UserAddress
                });
    return users.ToList();
}
Community
  • 1
  • 1
Yuliam Chandra
  • 14,494
  • 12
  • 52
  • 67