如果我说得对,那么您实际上是在说您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 映射的框架。