开发者

Straightforward way to send Entities over WCF

开发者 https://www.devze.com 2023-03-27 06:08 出处:网络
I\'m creating a website using Entity Framework (4.1), which exposes WCF services, and I have a Silverlight client communicating with the server over WCF. I want to send (and possibly receive) some Ent

I'm creating a website using Entity Framework (4.1), which exposes WCF services, and I have a Silverlight client communicating with the server over WCF. I want to send (and possibly receive) some Entities over the WCF service, without creating a proxy/wrapper etc. class. For example, I have a User entity type with Username, Password, Email fields (actually many more but shortened just to keep this simple) and I want to send this object to the Silverlight client. While sending Username and Email, I (obviously) don't want to send the Password property to the client. Now, I'm writing a wrapper with attribute [Serializable] and [DataContract] attributes, with fields having the [DataMember] attribute, which include开发者_高级运维s the fields only that I need, create a new instance, copy the values from the entity object, and send that proxy object. It works, but it's inconvenient and extremely painful. What I need is a mechanism where I can directly set the properties I want to be sent, and simply don't expose anything else. I can't change the code of the entity model (to add/edit attributes) as it gets auto-regenerated each time I touch the EDMX. Is there a way to accomplish exposing only the selected members to the clients?


To avoid the PROXY entites on the client, you can reuse the same entities (client and server side) by making sure that your client already references the server Entity assembly (assuming that you have mapped POCO's in EF and separated them out into their own assembly). Then check the advanced options in the server reference and ensure "Reuse Types in referenced Assemblies" is checked.

This will create a proxy Interface and client, but reuse the server Entities.

You can avoid the proxied interface as well by using the ClientBase<> generic instead of the service reference, although you will now need to strip out your Service side Interfaces (Service Contract interfaces) into a separate assembly and reference this on both Client and Server.

And as per your observation, if you don't mark a Property on your Entity as [DataMember], it won't be serialized. Since you've got the same entity both sides, fields like will come out as their default value (0, null etc) on the client.

0

精彩评论

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

关注公众号