Can early binding Types be refreshed in Dynamics CRM 2011 - entity

I've written a service that uses early binding types in dynamics CRM 2011. Now, I've updated one of my custom entity and created a few attributes to it of different types like new_visitdate and new_visitonly.
The problem is while updating the service and I am unable to find that my newly created attributes.
Can I refresh my early bind types so that I could retrieve latest attributes of an entity.

Yes, you will need to regenerate your early bound types whenever you make a change to the data model.

The Early Binding Doesn't have to be in Sync with the Actual CRM schema, as long as you don't attempt to set an attribute (or entity) in the EarlyBinding, that doesn't exist in the CRM instance. And of course, you will need to regen the entities if you want to reference the new attributes you've added.
I recommend using the Early Bound Generator to generate the entities. It uses the same CrmSvcUtil that the SDK provides, but puts a UI around it so you don't have to mess with the command line:

Related

Steps to use Entity Framework in 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.

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.

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.

EDM -> POCO -> WCF (.NET4) But transferring Collections causes IsReadOnly set to TRUE

Ok, this may sound a little 'unorthodox', but...using VS2010 and the new POCO t4 template for Entity Framework (Walkthrough: POCO Template for the Entity Framework), I can generate nice POCO's. I can then use these POCO's (as DTO's) in a WCF service essentially going from EDM all the way through to the client. Kinda what this guys is doing (POCO with EF 4.0 and WCF 4.0), except everything is generated automatically. I understand that an entity and a DTO 'should' be different, but in this case, I'm handling client and server, and there's some real advantages to having the DTO in the model and automatically generated.
My problem is, that when I transfer an entity that has a relationship, the client generated collection (ICollection) has the read-only value set, so I can't manipulate that relationship. For example, retrieving an existing Order, I can't add a product to the Products collection client-side...the Products collection is read-only.
I would prefer to do a bunch of client side 'order-editing' and then send the updated order back rather than making dozens of server round trips (eg AddProductToOrder(product)). I'd also prefer not to have a bunch of thunking between Entity and DTO. So all-in-all this looks good to me...except for the read-only part.
Is there a solution, or is this too much against the SOA grain?
The FixupCollection which is assigned to your ICollection is recreated as an Array when the deserialization occurs. Th'at's why your Products collection is read-only.
In order to modify this, you can use the option (existing at least on VS2010) in the "Add Service Reference", to change the Collection type to something else (Generic.List or Generic.Observable).
But, if you use the option to reuse type existing in existing assembly and referencing the assembly containing your entity, the previous option will not be applied to existing type and you will still have Array in your Products collection.
A workaround i use (only if you reuse type on client side and reference your entity assembly) is to modify the T4 template to check if the collection is read-only in the get of Products, and set an FixupCollection if it does:
if (<#=code.FieldName(navProperty)#>.IsReadOnly)
{
var newCollection = new FixupCollection<<#=code.Escape(navProperty.ToEndMember.GetEntityType())#>>(<#=code.FieldName(navProperty)#>);
newCollection.CollectionChanged += Fixup<#=navProperty.Name#>;
<#=code.FieldName(navProperty)#> = newCollection;
}
"la mouette" solution works with referenced assemblies:
We have the same problem, and we have noticed that the property IsReadOnly is setted to true after wcf serialization (Before that, the property value is false).
We have referenced assemblies. In the workaround proposed by "la mouette", use a parametrized constructor, but our POCO template doesn't have one.
We have modified the tt creating an empty constructor to invoke the base one, and that do the trick.