Steps to use Entity Framework in WCF - wcf

I have a question using Entity Framework in WCF. I am using .NET 4.5 with EF DbContext.
Here are the things I know to do to use EF in WCF. May be they are insufficient or some are not required.
Create EF ADO.NET Model.
Seperate the POCO classes to a seperate project (ProjectName: Entities) by using DbContext template generator.
Point the TT template of the POCO project to the edmx file in the data project (ProjectName: Data). "..\Data\MyEdmx.edmx"
Add [DataContract(IsReference(True))] and [DataMemeber] attributes in the .TT file of the POCO project so that the classes and properties will have the serialization attributes. Add Runtime.Serialization reference to the project and add the namespace to .TT file. This enables not to lose your attribute declaration while recreating the classes on a save of the .TT file or adding new entities.
Add ProjectName: Entities reference to Data project.
Turn off ProxyCreation and LazyLoading in the Context.tt file in the data project.
Add (ProjectName: Entities) and (ProjectName: Data) to your wcf service project.
Copy the EntityFramework connection string to your WCF project.
All your select methods in the service, must use .Include if you want the navigation objects to be populated. This gives better control when you want to load or or when you want limit data to show. Also, you don't get the child/related automatically due to lazyloading turned off.
Insert or Update or Delete, the service has to create the context and manually set the object state to be modified or added? Otherwise the changes will not be saved. Use the DbContext.Attach to attach and set the state of the entity appropriately Added,Modified, etc.
The problem I had was I could not find a good example of the steps to perform to use EF with WCF. I was able to see only bits and pieces. May be I am a late entrant to the WCF EF world hence could not find.
Not sure if I can use proxies WCF. I haven't understood completely the advantage of proxies yet.
I also read recommendations to use DTO as a layer between EF and the service. This requires a mapper to be in place. I don't know if I need it right away. But the idea is clear that it helps hide any unnecessary database columns showing in the business object. For example, audit columns such as created by, updated by etc we dont to show in the client.
I did not choose to use DataServices as I lose other binding options that I get from WCF. I don't know if it is a good thing to lose the simplicity of DataServices thinking about the future requirements of clients that require/support other binding mechanisms.
Any recommendations is appreciated.
Additional Update
I did find this in MSDN http://msdn.microsoft.com/en-us/library/ee705457(v=vs.100).aspx. Some of the links were pointing to pre-release documentation. But this gives some more ideas for me in using EF and WCF.
This articles shows how to use proxies with WCF, change tracking of POCO. This is a good start for me. If any one has more advise please provide your thoughts.
Update 2
*Another Excellent Link for N-Tier*
http://msdn.microsoft.com/en-us/magazine/dd882522.aspx
I am glad that the time I am spending is really educating me!

I progressed on using EF with WCF after lot of reading here and in other forums.
I followed the steps ahead. I was able to see the advantage of using DTO. This really allows you to hide fields that you don't need to expose to the client or other services. But I am holding back on introducing DTO due to time constraints.
I used context.Attach, context.Add and context.Entry.
I also did a small prototype to use WCF Data Service. That was very fast paced development. I am holding back on using WCF data services for now due to time constraint in learning its features.

Related

Use WCF Data Contract as model for MVC view

I have started working on an application which is structured as follows:
UI - ASP.Net MVC web application
Service Layer - WCF
Entities - a simple class library (exposed by WCF layer)
Data Layer - for database interactions.
Till now, I was defining my models in Models folder of my web application, but now as we have decided to expose them by WCF service (as this application will be consumed by other applications as well), I need some help here.
I tried putting all my model definitions in Entity layer which is exposed by WCF service decorating them with data annotations as well as DataContract attributes. Now, I am able to reference these entities to bind them with my views. But, data annotation validations are not working for me.
Can anybody please help me for a workaround for this ? I have been searching through web for solution but almost all tell me to put a reference of entity layer in web application which will be tight coupling that we do not want. and the other option is to redefine all entities with data annotations in models folder of my web application,which will be duplicate kind of coding.
Is there any better approach for this? Any help appreciated.
Update:
To consume WCF entities, I have put a service reference in my web application. Now, just to check I modified that Reference.cs file by decorating my data Member explicitly with [Required] attribute and it is working fine. but, I understand these changes will go away whenever service code is generated.
Is there any way I can bring that Data annotation attribute here? Kindly help.
As for me It's bad idea, DTO for transfer, Model for MVC.
Look like similar problem
Why You Shouldn’t Expose Your Entities Through Your Services
DTO’s Should Transfer Data, Not Entities

OData with WCF Data Services / Entity Framework

Apologies in advance, this is a long question.
(TL;DR : Does anyone have any advice on using the EF with dynamic fields exposed using WCF Data Services/OData)
I am having some conceptual problems with WCF Data Services and EF, specifically pertaining to exposing some data as an OData service.
Basically my issue is this. The database I am exposing allows users to add fields dynamically (user-defined fields) and it uses a system whereby these fields are added directly to the underlying SQL tables. Furthermore, when you want to add data to the tables you cannot use direct SQL, you have to go via an API that they provide. (it's SAP Business One, fwiw).
I have already sucessfully built a system that exposes various objects via XML and allows a client to update or add new entities into SBO by sending in XML messages, and although it works well it's not really suited to mobile apps as it's very XML-heavy and the entry point is an old-skool asmx webservice. I want to try to jazz it up for mobile development and use Odata with WCF or Web API. (I know I could change up to a WCF service, allow handing of JSON-format requests, and start returning JSON data, but it just seems like there must be a more...native...way)
Initially I had discounted the possibility of using the EF for this because a)Dynamic fields and b)the EF could only be read-only; adding/updating entities would have to be intercepted and routed to the SBO DI Server. However, I am coming back to thinking about it and am looking for some advice (negative or otherwise!) on how to approach.
What I basically want to do is this
Expose the base tables from SBO (which don't change except when they themselves issue a patch) as EF Entities, with all the usual relationy goodness. In fact I actually will not be directly exposing the tables, I will use a set of filtered SQL Views as the data sources as this ties in with various other stuff we do to allow exposing only certain data to 3rd parties.
Expose any UDFs a particular user has added as some kind of EAV sub-collection per entity.
Intercept any requests to ADD or UPDATE an object, and route these through an existing engine I have for interfacing with the SAP Data import services.
I suppose my main question is this; suppose I implement an EF entity representing a Sales Order which comprises a Header and Details collection. To each of these classes I stick in an EAV type collection of user-defined fields and values. How much work is involved in allowing the OData filtering system to work directly on the EAV colleciton (e.g for a client to be able to ask for Service/Orders/$filter=SomeUdfField eq SomeValue where this request has to be passed down into the EAV collection of the Order header entity)
Or is it possible, for example, to generate an EF Model from some kind of metadata on the fly (I don't mind how - code generation or model building library) that would mean I could just expose each entity, dyanmic fields included, as a proper EF Model? Many thanks in advance if you read this far :)
For basic crud to an existing EF context, WCF Data Services works out great. As soon as you want to add some custom functionality, as you described above it takes a bit more work.
What you described is possible, but you would need to build out your own custom data provider to handle the dynamic generation of metadata as well as custom hooks into add/update/delete.
It may be worth looking into WCF Data Services Toolkit, it's a custom provider which slaps a repository pattern over WCF Data Services for ease of use, but it does not provide the custom metadata generation.

Entity Framework Code First DTO or Model to the UI?

I am creating a brand new application, including the database, and I'm going to use Entity Framework Code First. This will also use WCF for services which also opens it up for multiple UI's for different devices, as well as making the services API usable from other unknown apps.
I have seen this batted around in several posts here on SO but I don't see direct questions or answers pertaining to Code First, although there are a few mentioning POCOs. I am going to ask the question again so here it goes - do I really need DTOs with Entity Framework Code First or can I use the model as a set of common entities for all boundaries? I am really trying to follow the YAGNI train of thought so while I have a clean sheet of paper I figured that I would get this out of the way first.
Thanks,
Paul Speranza
There is no definite answer to this problem and it is also the reason why you didn't find any.
Are you going to build services providing CRUD operations? It generally means that your services will be able to return, insert, update and delete entities as they are = you will always expose whole entity or single exactly defined serializable part of the entity to all clients. But once you do this it probably worth to check WCF Data Services.
Are you going to expose business facade working with entities? The facade will provide real business methods instead of just CRUD operations. These buisness methods will get some data object and decompose it to multiple entities in wrapped business logic. Here it makes sense to use specific DTO for every operation. DTO will transfer only data needed for the operation and return only date allowed to the client.
Very simple example. Suppose that your entities keep information like LastModifiedBy. This is probably information you want to pass back to the client. In the first scenario you have single serializable set so you will pass it back to the client and client pass it modified back to the service. Now you must verify that client didn't change the field because he probably didn't have permissions to do that. You must do it with every single field which client didn't have permission to change. In the second scenario your DTO with updated data will simply not include this property (= specialized DTO for your operation) so client will not be able to send you a new value at all.
It can be somehow related to the way how you want to work with data and where your real logic will be applied. Will it be on the service or on the client? How will you ensure that client will not post invalid data? Do you want to restrict passing invalid data by logic or by specific transferred objects?
I strongly recommend a dedicated view model.
Doing this means:
You can design the UI (and iterate on it) without having to wait to design the data model first.
There is less friction when you want to change the UI.
You can avoid security problems with auto-mapping/model binding "accidentally" updating fields which shouldn't be editable by the user -- just don't put them in the view model.
However, with a WCF Data Service, it's hard to ignore the advantage of being able to write the service in essentially one line when you expose entities directly. So that might make the most sense for the WCF/server side.
But when it comes to UI, you're "gonna need it."
do I really need DTOs with Entity Framework Code First or can I use the model as a set of common entities for all boundaries?
Yes, the same set of POCOs / entities can be used for all boundaries.
But a set of mappers / converters / configurators will be needed to adapt entities to some generic structures of each layer.
For example, when entities are configured with DataContract and DataMember attributes, WCF is able to transfer domain objects' state without creating any special classes.
Similarly, when entities are mapped using Entity Framework fluent mapping api, EF is able to persist domain objects' state in database without creating any special classes.
The same way, entities can be configured to be used in any layer by means of the layer infrastructure without creating any special classes.

OData WCF Data Service with NHibernate and corporate business logic

Let me first apologise for the length of the entire topic. It will be fairly long, but I wish to be sure that the message comes over clearly without errors.
Here at the company, we have an existing ASP.NET WebApplication. Written in C# ASP.NET on the .NET Framework 3.5 SP1. Some time ago an initial API was developed for this web application using WCF and SOAP to allow external parties to communicate with the application without relying on the browsers.
This API survived for some time, but eventually the request came to create a new API that was RESTfull and relying on new technologies. I was given this assignment, and I created the initial API using the Microsoft MVC 2 Framework, running inside our ASP.NET WebApplication. This took initially quiet some time to get it properly running, but at the moment we're able to make REST calls on the application to receive XML detailing our resources.
I've attended a Microsoft WebCamp, and I was immediatly sold by the OData concept. It was very similar then what we are doing, but this was a protocol supported by more players instead of our own implementation. Currently I'm working on a PoC (Proof of Concept) to recreate the API that I developed using the OData protocol and the WCF DataService technology.
After searching the Internet for getting NHibernate 2 to work with the Data Services, I succeeded in creating a ReadOnly version of the API that allows us to read out the entities from the internal business layer by mapping the incoming query requests to our Business layer.
However, we wish to have a functional API that also allows the creation of entities using the OData protocol. So now i'm a bit stuck on how to proceed. I've been reading the following article : http://weblogs.asp.net/cibrax/default.aspx?PageIndex=3
The above articly nicely explains on how to map a custom DataService to the NHibernate layer. I've used this as a base to continue on, but I have the "problem" that I don't want to map my requests directly to the database using NHibernate, but I wish to map them to our Business layer (a seperate DLL) that performs a large batch of checks, constraints and updates based upon accessrights, privledges and triggers.
So what I want to ask, I for example create my own NhibernateContext class as in the above articly, but instead rely on our Business Layer instead of NHibernate sessions, could it work? I'd probably have to rely on reflection alot to figure out the type of object I'm working with at runtime and call the correct business classes to perform the updates and deletes.
To demonstrate with a smal ascii picture:
*-----------------*
* Database *
*-----------------*
*------------------------*
* DAL(Data Access Layer) *
*------------------------*
*------------------------*
* BUL (Bussiness Layer) *
*------------------------*
*---------------* *-------------------*
* My OData stuff* * Internal API *
*---------------* *-------------------*
*------------------*
* Web Application *
*------------------*
So, would this work, or would the performance make it useless?
Or am I just missing the ball here?
The idea is that I wish to reuse whatever logic is stored in the BUL & DAL layer from the OData WCF DataService.
I was thinking about creating new classes that inherit from the EntityModel classes in the Data.Services namespace and create a new DataService object that marks all calls to the BUL & DAL & API layers. I'm however not sure where/who to intercept the requests for creating and deleting resources.
I hope it's a bit clear what I'm trying to explain, and I hope someone can help me on this.
The devil is in the details, but it sounds like the design you're proposing should work.
The DataService class is where you get to define the access rights applicable to everyone, configuration settings, and custom operations. In this scenario, I think you will be focusing more on the data context instead (the 'T' in DataService).
For the context, there are really two interesing paths: reads and writes. Reads happen through the IQueryable entry points. Writing a LINQ provider is a good chunk of work, but NHibernate already supports this, although it would return what I imagine we're calling DAL entities. You can use query interceptors to do access checks here if you can express those in terms that the database would understand.
The update path is from what I understand where you are trying to run more business logic (you mentioned validation, extra updates, etc). To do this, you'll want to focus on the IUpdatable implementation (IDataServiceUpdateProvider if you're using the latest version). Here you can use whichever objects you want - they could be DAL objects or business objects. You can do everything in the DAL and then run validation on SaveChanges(), or do everything on business objects if they validate as they go.
There are two places where you might 'jump' from one kind of objects to another. One is in the GetResource() API, where you get an IQueryable, presumably in term of DAL entities. The other is in ResolveResource(), where the runtime is asking for an object to serialize, just like it would get from an IQueryable, so it's presumably also a DAL entity.
Hope this helps - doing uniform access over non-uniform APIs can be hard, but often well worth it!

EF4: using Add Service Reference causes issues with STE(self tracking entities) not remember there changes?

I found an issue but it refers to the BETA version of VS 2010. I am interested in knowing if this issue has been fixed in RTM?
Basically it states (saw it via EF 4 Self Tracking Entities does not work as expected )
Make certain to reuse the
Self-Tracking Entity template’s
generated entity code on your client.
If you use proxy code generated by Add
Service Reference in Visual Studio or
some other tool, things look right for
the most part, but you will discover
that the entities don’t actually keep
track of their changes on the client.
I am very used to using Add Service Reference, and its always worked great for me in the past but of course I wasn't using STE (Self tracking entities). Is this problem still apparent with VS 2010 RTM and the STE template?
If I do create the proxy via code instead of add service then all the classes won't be created will they?
This is not an issue and it never was an issue. It is absolutly expected and correct behavior. STEs are classes which contains data and logic (the logic tracks changes).
When adding service reference your client proxy code is generated from service's metadata. Metadata are exposed in form WSDL. WSDL is XML based description of the service which also contains XSD description of transfered data types. XSD can describe only data format but not related logic implemented by the type. By default all unknown data types described in WSDL are generated on the client. So when you generate client proxy with all data types by Add service reference the tracking logic is lost.
To overcome this issue you have to do two things:
Create separate assembly and place all your STEs to this assembly. Then share this assembly among all involved layers (yes you have to use Add reference in your client).
Then you can use Add service reference with "Reuse types in referenced assemblies" checked.