【发布时间】:2016-12-20 12:20:15
【问题描述】:
我正在使用 Entity Framework 6 来构建 DB 模型。 我还使用 JSON 构建了基于 Web Api 2 的 Web 服务..
我的主要部分类定义如下所示: (从 EF 生成(来自 DB 的第一个代码),所以我不想在这里存储太多更改)
public partial class Animal
{
[Key]
[Column(Order = 0)]
public long AnimalId { get; set; }
[Key]
[Column(Order = 1)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public long SpeciesId { get; set; }
[Key]
[Column(Order = 2)]
public string AnimalName{ get; set; }
public string AnimalDescription{ get; set; }
public List<AnimalTags> AnimalTags= new List<AnimalTags>();
}
我还有另一个带有一些附加属性的部分类,我不想通过 Web Api 显示。
public partial class Animal
{
[JsonIgnore]
public bool IsNew { get; set; } = false;
[JsonIgnore]
public bool IsChanged { get; set; } = false;
}
那是我的 AnimalController :
public IHttpActionResult GetAnimals(long id)
{
Animal animal = (from an in db.Animal
where a.AnimalId == id
select a).FirstOrDefault();
animal.AnimalsTags= db.AnimalTags.Where(at=> at.AnimalId == animal.AnimalId).ToList();
if (animal == null)
{
return NotFound();
}
return Ok(animal);
}
我已经检查了 SO 和 MSDN 上的所有建议解决方案,但这些属性不起作用。 也许我在其他地方犯了错误?
感谢您的帮助。
编辑: DB Model 在其他项目,WebService 在另外一个项目,所以我通过 Reference 将 DB Model 链接到 WebService。
我的注册类在 Newtonsoft.Json 中的样子:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DataApi",
routeTemplate: "api/{controller}/{Id}",
defaults: new { Id = RouteParameter.Optional }
);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
config.Formatters.JsonFormatter.SerializerSettings =
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
Formatting = Formatting.Indented
};
}
【问题讨论】:
-
你试过 [NotMapped] 了吗?
-
@MMK:是的。但没有成功。
-
[ScriptIgnore(ApplyToOverrides = true)]
-
您在哪里发现应该使用
[IgnoreDataMember]或[ScriptIgnore]?均不适用于 WebAPI 的默认 JSON 序列化程序,即 Newtonsoft.Json。 -
@CodeCaster:我认为我写的很清楚,我没有使用 Newtonsoft.Json。
标签: c# json entity-framework serialization asp.net-web-api2