Retrieve EF4 POCOs using WCF REST services starter kit
Posted
by
muruge
on Stack Overflow
See other posts from Stack Overflow
or by muruge
Published on 2011-03-01T22:18:26Z
Indexed on
2011/03/06
8:10 UTC
Read the original article
Hit count: 539
I am using WCF REST service (GET method) to retrieve my EF4 POCOs. The service seem to work just fine. When I query the uri in my browser I get the results as expected.
In my client application I am trying to use WCF REST Starter Kit's HTTPExtension method - ReadAsDataContract() to convert the result back into my POCO. This works fine when the POCO's navigation property is a single object of related POCO. The problem is when the navigation property is a collection of related POCOs. The ReadAsDataContract() method throws an exception with message "Object reference not set to an instance of an object."
Below are my POCOs.
[DataContract(Namespace = "", Name = "Trip")]
public class Trip
{
[DataMember(Order = 1)]
public virtual int TripID { get; set; }
[DataMember(Order = 2)]
public virtual int RegionID { get; set; }
[DataMember(Order = 3)]
public virtual System.DateTime BookingDate { get; set; }
[DataMember(Order = 4)]
public virtual Region Region { // removed for brevity
}
}
[DataContract(Namespace = "", Name = "Region")]
public class Region
{
[DataMember(Order = 1)]
public virtual int RegionID { get; set; }
[DataMember(Order = 2)]
public virtual string RegionCode { get; set; }
[DataMember(Order = 3)]
public virtual FixupCollection<Trip> Trips { // removed for brevity
}
}
[CollectionDataContract(Namespace = "", Name = "{0}s", ItemName = "{0}")]
[Serializable]
public class FixupCollection<T> : ObservableCollection<T>
{
protected override void ClearItems()
{
new List<T>(this).ForEach(t => Remove(t));
}
protected override void InsertItem(int index, T item)
{
if (!this.Contains(item))
{
base.InsertItem(index, item);
}
}
}
And this is how I am trying retrieve a Region POCO.
static void GetRegion()
{
string uri = "http://localhost:8080/TripService/Regions?id=1";
HttpClient client = new HttpClient(uri);
using (HttpResponseMessage response = client.Get(uri))
{
Region region;
response.EnsureStatusIsSuccessful();
try
{
region = response.Content.ReadAsDataContract<Region>(); // this line throws exception because Region returns a collection of related trips
Console.WriteLine(region.RegionName);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
Would appreciate any pointers.
© Stack Overflow or respective owner