Entity Framework with POCO Serializable Classes and Lazy Loading - wcf

I have set up my POCO classes with ICollection for related objects. They are in a WCF Service, so I have decorated them with DataContract/DataMember. I do not use virtual properties for the related objects, because they create a proxy that won't serialize (I get a seemingly unrelated message, "The underlying connection was closed", but when I remove the virtual modifier, that goes away.)
What I am having trouble understanding is how to lazy-load the collections for related objects. I don't think the POCO's can do that for themselves, because they don't have access to the context.
For example, I have a Company class, which has an ICollection<Principals> property. I usually don't want to load all the Principals when I retrieve a Company, but I would like a reference to Company.Principals to go get them. Clearly, Company simply can't do that on its own.
What are folks doing to combine the desires to have (1) POCO objects, (2) typical WCF Serialization, and (3) lazy-loaded related properties?

Lazy loading requires proxies and virtual navigation properties. If you don't have proxies you must handle loading in different way. For example by using eager loading:
var companies = context.Companies.Include("Principals").ToList();
or with EF 4.1
var companies = context.Companies.Include(c => c.Prinicpals).ToList();
You know which operation should load related principals as well so using eager loading is not a problem. Using lazy loading in WCF service with serialization will always result to load whole object graph.

Related

Return Entity Framework objects from WCF

I am working on a WCF service to provide data to multiple mobile clients. Data model is Entity Framework 4.0. Schema is given below.
When i returnt he object of SysUser the result also contains the navigation properties and EntityKey and other EF related stuff. Is it possible that i get the pure object(only the database fields without the relationship etc).
Thanks
Update
the exception occures "Only parameterless constructors and initializers are supported in LINQ to Entities." on followign code:
return (from u in DataSource.SysUsers
where u.UserID == UserID
select new Player(u)
).FirstOrDefault();
You probably want to send DTOs across the wire rather than your EF objects.
You could use something like AutoMapper to populate your DTOs from the EF objects.
I think if you remove the virtual keyword in your SysUser model for the navigation properties, those will not be loaded. Later, if you need to load this properties, you can do it manually as stated here: http://msdn.microsoft.com/en-us/data/jj574232
Now, if you want to make SysUser travel through a WCF service, it is not a good idea. First, your service's client will need a reference to your Models Project... and that doesn't feels right. If you don't reference your Models, you will get a proxy for it, that is more or less the same as Joe R explained about DTOs.
Here is a related answer: https://stackoverflow.com/a/7161377/7720

How can I send POCO Entities through WCF Service when I don't want to track the entity *later*?

I have an ASP.NET MVC 4 project, where Controller calls a WCF Service layer, that calls Business Layer, that use a Repository of EF 5.0 Entities. Then the results are returned as POCO entities to the Controller.
It works fine while the WCF Service is directly referenced as a Library, but I know it won't work referenced as a Service because they will need to be serialized, and with ProxyCreation enabled this is not possible.
I don't want to create DTOs because I use generated POCO entities, that's why they exist in my humble opinion.
I want to track changes only before the POCO entities reach Service layer.
A lot of people talk about using DTOs even when they are identical to POCOs, if I do that, I could create auto-generated copied classes just with different names to be a "Proxy disabled POCO as DTO", what would be a little strange.
Could I kill the proxy class of a POCO, in a way the object could be serialized when returned from the Service layer?
Also I don't know if this idea is a good practice. But would be great to send "clean" entities to my Controllers, ready to me mapped to ViewModels.
I'm looking for performance too.
The problem is solved using ProxyDataContractResolver. We must use [Serializable] and [DataContract(IsReference=true)] too. With this combination, ProxyCreation can be enabled.
The way we handled this was by doing the following:
Customize the T4 generating the POCO classes so that it generates classes decorated with
[Serializable()] and [DataContract(IsReference=true)] attribute.
Both frontend (views) and backend (wcf service / business layer) references the POCO generated classes, since you won't be using proxy due to IsReference=true.
and that's basically it.
With this, you don't have to create DTO and just use the POCO classes both in backend and frontend.
Keep in mind though, that WCF using IsReference=true handles does not like redundant objects (so this would be an issue on some POCO classes with navigation properties).

How do lazily loaded POCO entities, entity framework and WCF work together?

If a project has used POCO for entities and uses entity framework and uses lazy loading then you have an "incomplete" object graph going back over the wire. So when a client uses the Entity is there some sort of proxy that will automagically load the remaining values? Do we have to create this proxy ourselves and wrap the original entity in it? Or is there an accepted pattern for identifying lazy loaded types which would then signal the client to make another call to the WCF?
Lazy loading with WCF usually doesn't work because your method looks like:
public List<MyPoco> GetData()
{
using (var context = new MyObjectContext())
{
return context.MyPocos.ToList();
}
}
As you see context is closed in method (you have to close context somewhere). But when the list is serialized it will try to lazy load dependent objects => exception because context is already closed. In WCF you should use eager loading.
Use flat DTO's, you probably don't want to expose your full domain to the client anyway. WCF is message-based, not Domain Driven.

What is Castle proxy factory in NHibernate?

What is Castle proxy factory in NHibernate? What is its task? What does proxy mean in this case?
Castle can be used (amongst others, you have the choice, you can also use LinFu, Spring.NET, ...) to create dynamic proxies of your entities.
By default, NHibernate uses dynamic proxies to represent your entities; by doing so, it is able to return an object to you when you retrieve some entity from the DB, without all properties being populated. By using a dynamic proxy, it will only populate the entity once you really refer to a property.
(So it is some kind of lazy loading; not to be confused with lazy loading of collections / associations though).
This behaviour is the reason why NHibernate wants you to create every property as virtual by default: NHibernate will create a new class using this Castle (or LinFu, ...) proxy provider which inherits from your entity, and it will override all the properties so that it can 'inject' the code that is necessary to retrieve the necessary data from the DB.
You can disable this behaviour by specifying 'lazy=false' in your entity mapping. (Although, I do think that even if you disable this feature, NHibernate will still require that you use one of the proxy factories).
When you are selecting an entity from ISession you are getting not real entity instance - you are getting proxy object.
This proxy object inherits your entity and used by NHibernate to track changes made to the fields.
see it: http://en.wikipedia.org/wiki/Proxy_pattern

Returning NHibernate mapping classes from WCF services

I have a server that handles the database access and a client that consumes the information. The communication from the client to the server is through a WCF service.
When the NHibernate POCO is returned from the service are all the objects in the object graph serialized? If so, is there a way to change it?
I'm also thinking of not returning the NHibernate POCO and instead return an object with only the essential information.
What do you do in these cases?
Use data-transfer objects to move the data from the server to the client. Your business (domain model) objects should not necessarily be exposed outside the core of the application, but should be considered a protected asset.
You can use AutoMapper to automate the translation from business objects to data-transfer objects.
Yeah, you probably want a DTO for this. It's usually considered better to not pass your data objects to the outside world, but also passing hibernate objects directly out of a service can give you some weird behavior, especially if you have lazily loaded collections.