Asp. net ядро ​​WebApi для возврата внешнего ключа в качестве значения - PullRequest
1 голос
/ 11 марта 2020

net Здесь я работаю на Asp. net ядре, используя Entity Framework Core (версия 3.1.2), и я использую мс sql сервер как моя БД

у меня есть два класса сущностей Region и страна

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

И мой Db context

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

и мой 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")));

    }

Строка подключения в appsettings. json

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

}

контроллер страны

// 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;
        }

когда я получаю значение путем передачи URL (http://localhost: 65177 / api / region / 10 ) в инструменте почтальона, оно возвращает значение как это

что я получаю

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

И что я ожидаю, это

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

Пожалуйста, кто-нибудь дать мне решение решить это ... заранее спасибо.

Ответы [ 2 ]

1 голос
/ 11 марта 2020

Использовать json игнорировать атрибут. Например, [JsonIgnore]

0 голосов
/ 12 марта 2020

Попробуйте добавить атрибут ниже в вашей модели Country (сначала добавьте ссылку using Newtonsoft.Json;)

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

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