2

我正在寻求一些关于以有效方式使用实体框架和从 MVC 应用程序调用的 WCF 服务的建议。

我有一个 ASP.NET MVC Web 应用程序作为表示层,它调用一个 WCF 服务,该服务执行所有数据操作。WCF 应用程序使用实体框架对 DB 执行操作。

问题是,根据正在呈现的页面,数据库所需的信息会发生变化,例如,如果我想显示所有用户的列表,我可能只想要他们的用户名,但 WCF 服务会返回整个模型,在处理大量记录时,这显然变得非常低效。

有什么方法可以提高效率,需要以某种方式在 Linq 语句中指定 Include 和 Select 的值

4

1 回答 1

1

如果我说得对,那么您实际上是在说您Models与您的需求不兼容Views

这就是为什么人们使用Data Transfer Objects (DTO)从数据服务返回的对象而不是实体本身的原因之一。

通常,您将需要将project / map您的实体放入 DTO 对象中。

例如,如果我想显示所有用户的列表,我可能只想要他们的用户名,但 WCF 服务会返回整个模型

对于这种特殊情况,您可以尝试这样的事情:

// 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);
}

此外,当使用 Asp.Net MVC 时,DTO可以用作您ViewModels的(参见此处)。

您还可以使用AutoMapper可以为您处理实体到 DTO 映射的框架。

于 2013-06-24T09:35:19.487 回答