Under what circumstances are RIA services navigation properties loaded? - entity-framework

We have a Silverlight 4 client connecting to RIA services. It's based on the standard "Business Application" Silverlight application in VS 2010. The objects we send to the client over RIA services are EF 4 entities that are POCO objects generated from our edmx by T4. Our RIA service is a LinqToEntitiesDomainService<> of our linq repository.
We have two Entities that share similar structure but are unrelated. Both are both have navigation property that represents a single instances of another entity. Both are retrieved using methods marked [Query]. For one entity the navigation property is always correctly populated when we try and access its value; for the other it is never populated, it always remains null (well it seems to hold an EntityRef<> object that points to a null entity). We have verified the relations in the edmx and the generated code on the client side, both seem to share the same structure, so we don’t understand why this difference in behavior is happening. Can anyone shed some light on the subject?
Many thanks,
Robert

Are you using the "[Include]" attribute and "Include" functions in one of your entities / domain services methods and not the other one? If so, this answer to a similar question might help you: If you create a DomainService, exposing an entity, can you access aggregate entities?

Cannot give any definite answer, but you could try by checking these things:
Is there any data in the database for the object that is null
Are the query parameters correct
Do you have a test on the server side to see that the data is available
Is there an attribute missing on one of the objects

Related

Getting familiar with Entity Framework when using existing database

We are currently rewriting an existing internal ASP.NET Web Forms application. Our application consists of a Web Api back end which uses Entity Framework 6 for data access and an front end which uses AngularJS.
We have an existing large database that I've created EF models using the Code-First Using Existing Database method and we are using data transfer object classes as inputs/outputs to our API methods so we aren't directly exposing our model classes. So basically, I'm trying to become proficient with EF, Web Api and AngularJS all at the same time. For the most part I'm fairly comfortable with the latter two, but for EF I haven't completely gotten comfortable with. I've watched a lot of the videos on Microsoft Virtual Academy but this is the first time I've had some hands-on experience with it.
We've been working on this application for a few months and so far we've only had to work with CRUD operations on our entities (POCO DTO's) which are flat objects with simple properties. However, we've finally come across some situations where we need to deal not only with our classes, but properties which are classes themselves; a parent-child relationship.
Therefore, I have the following questions:
I see that when we have a proper foreign key relationship in our DB, that virtual properties are created in EF, which from what I recall are to support lazy-loading. However, lazy-loading isn't really feasible in this environment where we are using web services (Web Api). Our object model does allow for some really large hierarchy of classes where a fully populated object and its children would mean a large amount of data would be passed around when that really isn't necessary, so in most cases a first level object is all we need. In some cases however, we do want to populate child classes, so my question is how do we do that, and where do we do that? I've looked at the automatically-generated code in the DB Context but we have also used scaffolded code to create our controllers. Which place do we need to do this? I've seen code samples showing how do to this but it hasn't said specifically where this code lies. It appears to be within a controller but I could be wrong.
If we do allow for 2- or more level hierarchy of objects, does EF automatically handle operations (updates, deletes, etc.) -- for example, if we have a "Company" object which has a collection of "Customer" objects, and we delete the "Company" object, do the related "Customer" objects get deleted too? Also, is a multi-step operation like that automatically performed within a transaction or do we need to explicitly set that up?
If I modify a model class or the DB context, seeing as this code is automatically-generated, that's generally bad practice as my changes could be overwritten, so I am assuming the controller code is where I want to make my changes. I am aware of database migrations but I have no experience with them and I am sure I'll need to use them at some point because I am fairly confident that our database may not have all the foreign key relationships necessary for EF to do everything we need at the moment.
I know this is a long post, but if anyone can give some guidance on how to do some of these things because it's not only me that's having to deal with this but I have two other developers on my team who are working on this project and we are all as inexperienced with this as the others are. Thanks
For the purpose of sending data across a web service, I'd suggest creating a DTO to hold the data you want to send and mapping your entities to the DTO instead of trying to send the entities themselves in your payload. It also protects your API from changes to your entity.
Cascading deletes are configurable, iirc, but I'm not 100% sure what the default is. Transactions are generally not implicit, so you will want to use those where you require them.
Not exactly sure what you are asking here. In general, how your entities/tables change depends on if you are using database-first or code-first. If you are using database-first (you will have a .edmx file in your solution that has the model matching your schema), you just update the SQL directly and update your entity model via the .edmx. If you use code-first, you will change the entities how you want them and run a database migration to update your database to match.
MSDN article about code-first migration: https://msdn.microsoft.com/en-us/data/jj591621.aspx

Is there a DataServiceContext.Set(type) equivalent to DbContext.Set(type)

I have recently created a pretty robust API built around Entity Framework's DbContext. I am using a lot of metadata programming and taking advantage of the fact that I can get my data with a call like DbContext.Set(typeof(Customer)). Only, in my API I do not know at compile time what type I will be passing to the Set method. This is working very well with EntityFramework and I would like to add another layer abstraction and have it work with both EntityFramework or DataServiceContext. So, I really have two questions.
Firstly, and more specifically, is there a DataServiceContext (i.e. odata/wcf) equivalent to the DbContext.Set(type) method?
Secondly, and more generally, is there a good resource that compares the APIs provided by DbContext with DataServiceContext?
EntityFramework and DataServices client API should not be mixed. Even though they look similar they are not. DbSet represents entity set. I don't think there is a strong contract around entity sets in DataServiceContext. Instead the name of the entity set is passed to methods that need to know this (e.g. look at DataServiceContext.AddObject() or DataServiceContext.CreateQuery() methods) as strings. In some sense it makes it much easier to program the DataServiceContext dynamically. On the other hand you still need to know what is on the other side of the pipe (i.e. the server). As said above WCF Data Services and EntityFramework are different technologies (even though they can work together) and their APIs, though similar, serve different purposes. Therefore comparing them would be like comparing apples to oranges.
The DbContext API in the client side is not the same from DbContext on server side. The main goal is to expose the data and model, which can be done pretty well. I think you may be overengeneering your app, since WCF Data Services can provide enough funcionalities.
Here is a link from Ladislav Mrnka, who is very good at entity framework, he shows how you could expose your robust api with WCF Data Services.
Implement WCF Data Service using the Repository Pattern

EF + WCF in three-layered application with complex object graphs. Which pattern to use?

I have an architectural question about EF and WCF.
We are developing a three-tier application using Entity Framework (with an Oracle database), and a GUI based on WPF. The GUI communicates with the server through WCF.
Our data model is quite complex (more than a hundred tables), with lots of relations. We are currently using the default EF code generation template, and we are having a lot of trouble with tracking the state of our entities.
The user interfaces on the client are also fairly complex, sometimes an object graph with more than 50 objects are sent down to a single user interface, with several layers of aggregation between the entities. It is an important goal to be able to easily decide in the BLL layer, which of the objects have been modified on the client, and which objects have been newly created.
What would be the clearest approach to manage entities and entity states between the two layers? Self tracking entities? What are the most common pitfalls in this scenario?
Could those who have used STEs in a real production environment tell their experiences?
STEs are supposed to solve this scenario but they are not silver bullet. I have never used them in real project (I don't like them) but I spent some time playing with them. The main pitfalls I found are:
Coupling your data layer with your client application - you must share entity assembly between projects (it also means it is .NET only solution but it should not be a problem in your case)
Large data transfers - you pass 50 entities to clients, client change single entity and you will pass 50 entities back. It will require some fighting with STEs to avoid passing unnecessary data
Unnecessary updates to database - normally when EF works with attached entities it track changes on property level but with STEs it track changes on entity level. So if user modify single property in entity with 100 properties it will generate update with setting all of them. It will require modifying template and adding property level change tracking to avoid this.
Client application should use STEs directly (binding STEs to UI) to get most of its self tracking ability. Otherwise you will have to implement code which will move data from UI back to self tracking entity and modify its state.
They are not proxied = they don't support lazy loading (in case of WCF service it is good behavior)
I described today the way to solve this without STEs. There is also related question about tracking over web services (check #Richard's answer and provided links).
We have developed a layered application with STE's. A user interface layer with ASP.NET and ModelViewPresenter, a business layer, a WCF service layer and the data layer with Entity Framework.
When I first read about STE's the documentation said that they are easier then using custom DTO's. They should be the 'quick and easy way' and that only on really big projects you should use hand written DTO's.
But we've run in a lot of problems using STE's. One of the main problems is that if your entities come from multiple service calls (for example in a master detail view) and so from different contexts you will run into problems when composing the graphs on the server and trying to save them. So our server function still have to check manually which data has changed and then recompose the object graph on the server. A lot has been written about this topic but it's still not easy to fix.
Another problem we ran into was that the STE's wouldn't work without WCF. The change tracking is activated when the entities are serialized. We've originally designed an architecture where WCF could be disabled and the service calls would just be in process (this was a requirement for our unit tests, which would run a lot faster without wcf and be easier to setup). It turned out that STE's are not the right choice for this.
I've also noticed that developers sometimes included a lot of data in their query and just send it to the client instead of really thinking about which data they needed.
After this project we've decided to use custom DTO's with automapper from server to client and use the POCO template in our data layer in a new project.
So since you already state that your project is big I would opt for custom DTO's and service functions that are a specifically created for one goal instead of 'Update(Person person)' functions that send a lot of data
Hope this helps :)

MVC3 App/Service Layer/Repository Layer/POCO Classes/EF4 - Questions!

I am new to this whole design concept, and in reading for the last few weeks I have gathered a lot of information, but it seems scattered and conflicted. Terms are mixed, and I am just having a hard time wrapping my mind around this.
The pattern I am using is like this and assume the flow as follows:
MVC Application
The controller(s) process the request/response from the client for a given view. Inside the controllers action methods, they contact the services (Service Layer) and either request objects to build the view models, and sen the objects from the view models back.
View Models
I am using strongly typed view models to and from the views.
Are view models DTO's? Should they contain just simple properties like Name, AddressLine1, Address City, etc, or should they contain complex properties, multiple objects, etc.
Is the validation in the view model. If so would it be validation like required fields, field length, etc. Then validation like user name already exists, or where you would need to interact with other objects in the service layer?
Can the view models just contain the POCO classes returned from EF, or should I be using the AutoMapper?
If using AutoMapper and DTO, are DTO's clones of the POCO classes?
Would you map in the controller, view model, or in the service layer below?
Services
To me, the service(s) are objects that contact the repository(s) to get POCO objects back from the EF. This is where all of my business logic is. Once the service hands an object back to a repository to be persisted to the EF, they are considered valid objects. Is this correct?
Repositories
There is no business logic in them, they are just used to transport objects between the service(s) and the EF. Is this correct? I am implementing Interfaces here with generic repository. Then you could extend the generic repository for special needs?
Questions About Terminology
1) Is a business object equal to a domain object? How much logic should a domain object contain?
2) Is the domain model the EF model? I am using the Model-First approach.
3) Dependency Injection - Should I be using this? I understand how it works, just don't get the real benefit. I was playing with Ninject.
I think the community would benefit from some sort of wiki that contained all the best practices with code samples. Is there something like that out there? A lot of the samples out there are very simple, and a lot of the Microsoft samples do not use this pattern even when claiming to.
Thanks in advance to everyone who has and will help me with this.
BTW - I think StackOverflow needs a little, "Buy Me A Beer" button next to the "Accept Answer" checkbox :)
Are view models DTO's?
Could be considered a sort of data transfer objects between the controller and the view.
Should they contain just simple properties like Name, AddressLine1, Address City, etc, or should they contain complex properties, multiple objects, etc.
Ideally simple properties but could also aggregate other view models but no models there (ex: like EF models).
Is the validation in the view model.
There are two type of validation logic: business validation (ex. username already exists) which goes into the service layer and UI validation (ex: username is required) which goes into the view model.
Can the view models just contain the POCO classes returned from EF, or should I be using the AutoMapper?
No EF in view models. View models are POCO classes with simple properties and other complex properties pointing to other view models. They could also contain methods in order to properly format the data that will be presented on the particular view those models were intended for.
If using AutoMapper and DTO, are DTO's clones of the POCO classes?
Not sure I understand this question.
Would you map in the controller, view model, or in the service layer below?
The controller.
To me, the service(s) are objects that contact the repository(s) to get POCO objects back from the EF. This is where all of my business logic is. Once the service hands an object back to a repository to be persisted to the EF, they are considered valid objects. Is this correct?
Yes.
Is the domain model the EF model?
If you are using EF Code first approach then yes, otherwise no (if EF pollutes the domain with EF specific attributes and classes).
There is no business logic in them, they are just used to transport objects between the service(s) and the EF. Is this correct?
Yes.
I am implementing Interfaces here with generic repository. Then you could extend the generic repository for special needs?
Yes, but don't get too fancy. Normally Repositories are for CRUD operations. It's services that should contain the business logic.
Is a business object equal to a domain object?
Yes.
How much logic should a domain object contain?
This will depend on the amount of domain logic you have for the particular project you are working and on any existing domain logic you could reuse from older projects you or someone else have worked on.
Dependency Injection - Should I be using this?
Yes, absolutely.
I understand how it works, just don't get the real benefit
It provides weaker coupling between the different layers of your application which in turns makes them easier to unit test and reuse in other projects.
I think the community would benefit from some sort of wiki that contained all the best practices with code samples.
I agree.
Is there something like that out there?
I doubt it.
BTW - I think StackOverflow needs a little, "Buy Me A Beer" button next to the "Accept Answer" checkbox
Can't agree more.

What's the best POCO status tracking strategy? (EF)

So I was reading about Entity Framework and based on my agile development scenario I decided to go with POCO objects.
But now I'm having some extra problems I don't know how to get away with.
I'm working with RIA services and Silverlight so when I'm going to Save an object of the server side I have to attach the object to an ObjectContext. The thing is that I must then change the ObjectState to Added or Modified.
So my question is what's the best approach to really know what state to change it to. I saw in Julia Lerman's book that she uses a State attribute in her POCO objects and she takes care managing that state on the client side before sending the object to the server. That state then is used to change the real EntitySate once attached.
I've also seen other samples where the Insert implementation checks on the Key of the Entity (object) to know whether it is new or not. For example, if ProjectId in my Project entity is 0 (zero) I know it has to be a new object.
To be honest I don't like any of those approaches because in both cases my developers have to do some extra-work to actually save the object.
I'd like the know pros and cons of both solutions and hopefully a new (better) solution I'm still not seing.
You can still have self tracking entities and poco. In visual studio if you search the community templates there is a self tracking poco template. this is what you want to use. If you can find the template look for your entities using Ientitywithobjecttracker.
http://msdn.microsoft.com/en-us/library/dd456848.aspx