views:

107

answers:

1

I'm on the process of creating an API in much the same way Hanselman showed it could be done for Stackoverflow. I have a bunch EntityObject Entity Framework generated classes and a DataService thingy to serialize them to Atom and JSON. I would like to expose some generated properties via the web service. Think FullName as generated by concatenating First- and Lastname (but some are more complex). I have added these to a partial class extending the Entity Framework EntityObject and given them the [DataMemberAttribute()] attribute, yet they don't show up in the service. Here's an example attribute (set is thrown in for good measure, doesn't work without it either):

    [DataMemberAttribute()]
    public string FullName
    {
        get
        {
            return (this.Firstname ?? "") + " " + (this.Lastname ?? "");
        }
        set { ;}
    }

According to these discussions on msdn social, this is a known issue. Has anyone found good workarounds or does anyone have suggestions for alternatives?

A: 

I had the same issue exposing Entity objects over a WCF service and used the workaround you linked to here which is to add the following attribute to the properties to force them to be serialized.

[global::System.Runtime.Serialization.DataMemberAttribute()] 

I haven't found any 'nicer' ways of getting this working.

For example, given an entity called Teacher with fields Title, Forenames and Surname you can add a partial class for Teacher something like:

public partial class Teacher
{
    [global::System.Runtime.Serialization.DataMemberAttribute()] 
    public string FullName
    {
        get { return string.Format("{0} {1} {2}", Title, Forenames, Surname); }
        set { }
    }
}

Then as long as your WCF Service interface references this class then the extra properties are serialised and available for consumers of the service.

e.g.

[OperationContract]
List<Teacher> GetTeachers();
Nelson
hm, doesn't seem to be working though. What entities are you serilizing?
friism
I've added a more detailed example to the answer above.
Nelson
I think this requires EF4 to work. @Nelson - can you confirm that you are have .NET framework 4.0?
Antony Highsky