1

I am using Entity Framework 6 to build a model of DB. I've got also web service built on Web Api 2 with JSON..

My main partial class definition looks like that: (Generated from EF (first code from DB) so I don't want to store here too much changes )

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

and I've got also another one partial class with some additional properties, which I don't want to show through Web Api.

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

That's my 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);
}

I've checked all suggested solution on SO and MSDN but those attributes are not working. Maybe I made a mistake somewhere else?

Thanks for any help.

Edit: DB Model is in other project and WebService is in another one, so I am linking DB Model to WebService through Reference.

How my register class looks like with 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
            };
    }
Wiktor
  • 754
  • 1
  • 7
  • 24
  • did you try [NotMapped] ? – MMK Dec 20 '16 at 12:23
  • @MMK : Yes. But without success. – Wiktor Dec 20 '16 at 12:27
  • [ScriptIgnore(ApplyToOverrides = true)] – MMK Dec 20 '16 at 12:29
  • Where did you find that you should use either `[IgnoreDataMember]` or `[ScriptIgnore]`? Neither apply to the default JSON serializer for WebAPI, being Newtonsoft.Json. – CodeCaster Dec 20 '16 at 12:31
  • @CodeCaster: I've thought that I wrote that clearly that I am not using Newtonsoft.Json. – Wiktor Dec 20 '16 at 12:46
  • You're using WebAPI 2, which does. If you changed the default serializers, then show how you did that in your question. – CodeCaster Dec 20 '16 at 12:58
  • @CodeCaster: You did not even read my question! 1. I've wrote that I am not using Newtonsoft.Json. 2. I've wrote that I am using DataContract and DataMember attributes, but they are not working for my partial class. I've checked before this linked solution and as you can see it's not working. That's why I've created new question. – Wiktor Dec 20 '16 at 12:59
  • I'll repeat myself: if you replaced the default serializers, then show how you did that. For all we know, you did it incorrectly, and are indeed still on the default Newtonsoft.Json, which comes with WebAPI 2. The rest of your question is irrelevant. It's not about Entity Framework, it's not about partial classes (they get compiled into one, **if** they're in the same assembly and namespace). You could reproduce this with a single `Foo` class with two properties, one annotated and one not. – CodeCaster Dec 20 '16 at 13:02
  • CodeCaster: Ok, I went your way. I included Newtonsoft.Json into my project with DB Model, and into my project with ws. I've removed from my solution any GlobalConfigurations for using DataContractJsonSerializer and even then JsonIgnore is not working. I am wondering if this is not happening because of that, I am storing DB Model in separate Project, and WS in another one. Maybe some how it's because of that. – Wiktor Dec 20 '16 at 13:22
  • @CodeCaster : I've edited my question to include Newtonsoft.Json. But still without any success. Those properties with [JsonIgnore] are still included into response from WS. – Wiktor Dec 20 '16 at 13:38
  • So with `[JsonIgnore]` and the serializers untouched, the above code still returns a JSON object with the properties `isNew` and `isChanged`? – CodeCaster Dec 20 '16 at 14:28
  • @CodeCaster : Yes. I am looking for issue for hours. And I thought that I need fresh eye on that because I can't find anything. – Wiktor Dec 20 '16 at 14:31
  • I still can't shake the feeling there's something custom you're not showing. What is currently in your question should just work out of the box with Web API 2. Are you sure there's no other code overriding the default JSON formatter? Is this everything there is to the `Animal` class, or did you hide something? – CodeCaster Dec 20 '16 at 14:36
  • @CodeCaster : That's my whole Register class which is pretty default. That's also my whole Animal class model with partial class with those two properties. That's my also whole controller. I've got also another controllers but they are basically the same, just for different data. – Wiktor Dec 20 '16 at 14:46
  • @CodeCaster : Just for your information, I was able to make it work after cleaning each project. I am still not sure why it doesn't work before. I am happy to use that for now. Thank you for your help. Best regards! – Wiktor Dec 20 '16 at 15:31
  • Well thanks for that update! Like I said, it should work. :P – CodeCaster Dec 20 '16 at 15:32
  • Attributes go away when I save edmx File. How do I preserve the attributes ? – Sujay U N Jul 09 '19 at 07:17

1 Answers1

1

I think you are looking for [JsonIgnore] for the Json serializer or [IgnoreDataMember] for the default XML serializer.

But I can see in your code that you are using [DataContract], you can definitely do this also:

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

    //ignored
    public string IgnoredProp { get;set; }
}
jomsk1e
  • 3,585
  • 7
  • 34
  • 59
  • I am not using Json.NET, I am using DataContractJsonSerializer. So I can't us e [JsonIgnore]. And to the second part, as you can see, in partial class I don't have [DataMember] attributes. – Wiktor Dec 20 '16 at 12:51