Mike Norgate
Mike Norgate

Reputation: 2431

ASP.NET MVC N-Tier application with WCF and entity framework efficient loading

I am after some advice on using entity framework in an efficient way with a WCF service called from an MVC application.

I have a ASP.NET MVC web application as the presentation layer that calls through to a WCF service which does all the data manipulation. The WCF application uses entity framework to perform the operations on the DB.

The problem is that depending on the page that is being rendered the information required from the DB will change, for example if I want to show a list of all the users I might just want their username but the WCF service would return the whole model, this obviously becomes very inefficient when working with large numbers of records.

Is there any ways to make this more efficient, need to somehow be able to specify the values for Include and Select in the Linq statements

Upvotes: 2

Views: 2082

Answers (1)

haim770
haim770

Reputation: 49095

If i get you right, you're actually saying that your Models are not compatible with the needs of your Views.

That is (one of the reasons) why people are using Data Transfer Objects (DTO) as the objects returned from the data service, and not the entities themselves.

Usually, you will need to project / map your entities into the DTO object.

for example if I want to show a list of all the users I might just want their username but the WCF service would return the whole model

For this particular scenario you could try something like this:

// Your 'User' Entity
public class User : BaseEntity
{
    public int Id { get; set; }
    public string Username { get; set; }
    public string Email { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public virtual ICollection<Phone> Phones { get; set; }
}

// Base class for all 'Mappable' DTOs
public abstract class Mappable<ENTITY, DTO> where ENTITY : BaseEntity
{
    public abstract DTO ToDTO(ENTITY entity);
}

// Your DTO (specific to your grid needs)
public class UsersGridDTO : Mappable<User, UsersGridDTO>
{
    public int Id { get; set; }
    public string Username { get; set; }

    public override UsersGridDTO ToDTO(User entity)
    {
        return new UsersGridDTO
        {
            Id = entity.Id,
            Username = entity.Username
        };
    }
}

// In your WCF data service
public IEnumerable<DTO> GetData<DTO>() where DTO : Mappable<Entity, DTO>, new()
{
    return efContext.Users.Select(new DTO().ToDTO);
}

Also, When using Asp.Net MVC, the DTOs can be used as your ViewModels as well (see here).

You can also use frameworks like AutoMapper that can handle the Entity to DTO mapping for you.

Upvotes: 1

Related Questions