Asp .net core WebApi to return Foreign key Id as value

Viewed 1697

net Here I'm working on Asp .net core using Entity Framework Core(version 3.1.2) and i'm using mssql server as my DB

i have two entity class Region and country

Region.cs

[Key]
    public int Id { get; set; }
    [Column(TypeName ="nvarchar(20)")]
    [Required]
    public string Code { get; set; }
    [Column(TypeName = "nvarchar(150)")]
    [Required]
    public string Description { get; set; }
    [Column(TypeName = "Bit")]
    [Required]
    public Boolean Active { get; set; }

Country.cs

[Key]
public int Id { get; set; }

[Required]
public string Code { get; set; }
[Column(TypeName = "nvarchar(150)")]
[Required]
public string Description { get; set; }
[Column(TypeName = "Bit")]
[Required]
public Boolean Active { get; set; }
[Required]
public int RegionId { get; set; }
[ForeignKey("RegionId")]
public virtual Region Region { get; set;}

And my Db context

    public class MasterContext: DbContext
  {
    public MasterContext(DbContextOptions options):  base(options)
    {}
    public DbSet<Region> regions { get; set; }
    public DbSet<country> countries { get; set; }
  }

and my startup.cs

services.AddMvc()
           .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
           .AddNewtonsoftJson(options => {
             var resolver = options.SerializerSettings.ContractResolver;
             if (resolver != null)
               (resolver as DefaultContractResolver).NamingStrategy = null;
           });
  services.AddControllers();
  services.AddDbContext<MasterContext>(options =>
  options.UseSqlServer(Configuration.GetConnectionString("dev")));

    }

connection String in appsettings.json

**"ConnectionStrings": {
"dev": "Server=ADMIN;Database=MASTERS;User Id=vibe;Password=vibe"

}

country controller

// GET: api/countries/5
        [HttpGet("{id}")]
        public async Task<ActionResult<country>> Getcountry(int id)
        {
            var country = await _context.countries.Include(i => i.Region).FirstOrDefaultAsync(i => i.Id == id);

            if (country == null)
            {
                return NotFound();
            }

            return country;
        }

when i get the value by passing the Url(http://localhost:65177/api/regions/10) in the postman tool it returns value like this

what i get

    {
    "Id":10,
    "Code":"inn",
    "Description":"india",
    "Active":true,
    "RegionId":5,
    "Region": {
    "Id":5,
    "Code":"me",
    "Description":"middle east",
    "Active":true
}
    }

And what i'm expecting is this

{
"Id":10,
"Code":"inn",
"Description":"india",
"Active":true,
"RegionId": {
"Id":5,
"Code":"me",
"Description":"middle east",
"Active":true
}
}

pls anyone give me a solution to solve this...thanks in advance.

2 Answers

Use json ignore attribute. For example, [JsonIgnore]

Try to add below attribute in your Country model(add a reference of using Newtonsoft.Json; firstly)

[Required]
[JsonIgnore]
public int RegionId { get; set; }

[ForeignKey("RegionId")]
[JsonProperty("RegionId")]
public virtual Region Region { get; set;}
Related