简体   繁体   中英

Deserialize JSON object into a class object, but few properties needs to be remapped

I have class like this

public partial class KipProjectMaster
{
    public int Id { get; set; }
    public string ProjectCode { get; set; }
    public string ProjectName { get; set; }
    public string ProjectActive { get; set; }
    public string ProjectLevel { get; set; }
}

THis is actually the model class of the table ProjectMaster in SQL and its using entity framework. I can add and save items into the table without any issue. But recently there is change in JSON fields Project_Code and Project_Name. Others are same. Actually in my actual model/table there are around 35 columns. So how canI handle the situation without renaming the model or table. Do I need to inherit from this class and use any mapping or any better way?

Your entity class is an entity class and your JSON class is a JSON class. Those are two entirely different purposes and so you should not reuse nor inherit those classes. They shouldn't even know about each other.

You map from one to the other in your controller or business logic.

This total disconnect allows you to modify your database schema without your JSON API breaking, and vice versa.

Sure, you can put [JsonProperty(Name="Foo")] above your string Foo { get; set; } string Foo { get; set; } string Foo { get; set; } column property, but now you're mixing two purposes. You can't change Foo's datatype anymore without breaking something, you can't move it to another table (ie another class), you can't remove it when it's not necessary anymore, you can't mark it [Required] because that means something else in both contexts, you can't have a property Foo in the database that has no relation whatsoever to Foo in the DTO, and so on.

See also:

And many others.

Note that it doesn't matter whether you apply this to your own API (exposing your DTOs) or consuming someone else's API (storing their DTOs as-is in your database); the drawbacks apply to both.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM