开发者

WCF Data Service, serialize additional properties from Entity Framework partial classes

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 Fir开发者_如何学运维st- and LastName (but some are more complex). I have added these to a partial class extending the Entity Framework EntityObject and given them the [DataMember] 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):

[DataMember]
public string FullName
{
    get
    {
        return (this.FirstName ?? "") + " " + (this.LastName ?? "");
    }
    set { }
}

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


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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜