为什么Web Api包含未投影的响应属性

时间:2014-08-01 14:20:09

标签: entity-framework-6 asp.net-web-api2

我有一个视图模型

public class MyViewModel
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Position { get; set; }
        public string Email { get; set; }
        public string Office { get; set; }
        public DateTime? StartDate { get; set; }
        public int? Age { get; set; }
        public int? Salary { get; set; }
        public int? Extn { get; set; }
    }

我正在对我的实体进行投影

 public List<ViewModel.StaffViewModel> GetAll()
        {
            var context = new GistDemoDbEntities();

            var model = context.Staff
                .Select(s => new ViewModel.StaffViewModel
                {
                    FirstName = s.FirstName,
                    LastName = s.LastName,
                    Position = s.Position,
                    Salary = s.Salary
                }).ToList();

            return model;
        }

并使用Web Api作为json返回,但是在响应中我发现它包含了在视图模型中使用vlaue null定义的其他属性。我只想在响应中拥有我需要的那些属性,它们怎么可能?

1 个答案:

答案 0 :(得分:0)

你可以:

  • 从ViewModel中删除它们,视图模型应该只包含 无论如何你打算用什么。

  • 在属性上使用[JsonIgnore]以防止JSON.Net映射 它们。

Json Ignore是一个属性,请看这里;

http://james.newtonking.com/json/help/index.html?topic=html/SerializationAttributes.htm

相关问题