2016-12-20 6 views
0

私はEntity Framework 6を​​使用してDBのモデルを構築しています。 私は私の主な部分クラス定義はそのように見えます..またC#WebApi 2. JSONシリアル化。部分クラスからプロパティを除外します

を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を介して表示したくないいくつかの追加のプロパティ、とも別の部分クラスを持っています。私のAnimalControllerだ

public partial class Animal 
{ 
    [JsonIgnore] 
    public bool IsNew { get; set; } = false; 
    [JsonIgnore] 
    public bool IsChanged { get; set; } = false; 
} 

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モデルは他のプロジェクトにあり、WebServiceは別のものです。そのため、DBモデルを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 
      }; 
    } 
+0

あなたは[NotMapped]てみたのですか? – MMK

+0

@MMK:はい。しかし成功なし。 – Wiktor

+0

[ScriptIgnore(ApplyToOverrides = true)] – MMK

答えて

0

は、私はあなたがJson serializerまたは[IgnoreDataMember]デフォルトのXMLシリアライザのための[JsonIgnore]を探していると思います。

しかし、私はあなたが[のDataContract]使用しているあなたのコード内で見ることができ、あなたは間違いなくもこれを行うことができます:

[DataContract] 
public class YourClass 
{ 
    [DataMember] 
    public int Id { get; set; } 
    [DataMember] 
    public string Prop1 { get; set; } 

    //ignored 
    public string IgnoredProp { get;set; } 
} 
+0

私はJson.NETを使用していません。DataContractJsonSerializerを使用しています。だから私は私たち[JsonIgnore]はできません。 2番目の部分には、分かるように、部分クラスでは[DataMember]属性がありません。 – Wiktor

関連する問題