0

My requirement is to create common class library to use between EntityFramework project and JSON serialization project.I ended up with below class and properties which is decorated by Newtonsoft.Json and System.Runtime.Serialization attributes.

I feel, it's over burden. Can I use only Newtonsoft.Json attributes, so that I can remove all System.Runtime.Serialization attributes. If I do so, will my code first entity framework able to generate required schema in database?

[DataContract]
public partial class CompanyGroup:BaseEntity
{
    [DataMember(Name = "Id")]
    public string Id { get; set; }

    [JsonProperty("Name", Required = Required.Always)]
    [Required]
    [DataMember(Name = "Name")]
    public string Name { get; set; }

}

Also, I see [JsonRequired] attribute, how it is different from [Required]?

Is System.ComponentModel.DataAnnotations is enough for EF?

Basically what is the best practice while writing the common class libraries?

kudlatiger
  • 3,028
  • 8
  • 48
  • 98
  • 1
    `I feel, it's over burden.` Unless there is another way to achieve it with fewer attributes, it is not excessive. – mjwills Feb 24 '19 at 05:38
  • 2
    Your class violates [SRP](https://en.m.wikipedia.org/wiki/Single_responsibility_principle) and that will lead to this. – Sir Rufo Feb 24 '19 at 05:47
  • @SirRufo Okay, but if i go by that route I will end up with duplicate classes and maintaining the code is hard. Basically I am getting json input and I am storing it in DB after serialization. "Id" will not come from "json" input, but DB shall have ID column which may be guid. – kudlatiger Feb 24 '19 at 05:53
  • 1
    Well, I heard such arguments against SOLID too much. You should watch some Uncle Bob videos :o) – Sir Rufo Feb 24 '19 at 06:04
  • 2
    Usually you can omit explicitly providing the property name if it’s serialized name matches the properties name. Also you can comma-separate multiple attributes, so you could just write `[JsonProperty(Required = Required.Always), Required, DataMember]` to make it less verbose. – ckuri Feb 24 '19 at 08:46
  • https://stackoverflow.com/questions/38503146/combining-multiple-attributes-to-a-single-attribute – Shahar Shokrani Feb 24 '19 at 09:04

0 Answers0