C# Entity Framework Создать API, запрашивающий слишком много информацииC#

Место общения программистов C#
Ответить
Anonymous
 C# Entity Framework Создать API, запрашивающий слишком много информации

Сообщение Anonymous »

Я создал таблицу инвентаризации, в которой есть InventoryHistory и RestockRecord, имеющие внешний ключ, который необходим для идентификатора инвентаря.

Код: Выделить всё

public class Inventory : BaseEntity
{
public string InvName { get; set; }
public int InvQuantity { get; set; }
public double InvPrice { get; set; }
public Employee Employee { get; set; }

public ICollection InventoryHistory { get; set; }
public ICollection RestockRecord { get; set; }
}

public abstract class BaseEntity
{
[Key]
public long ID { get; set; }
public DateTime CreatedAt { get; set; } = DateTime.Now;
public DateTime UpdatedAt { get; set; } = DateTime.Now;
public long CreatedBy { get; set; } = 1;

}
Это один из примеров таблицы InventoryHistory.

Код: Выделить всё

public class InventoryHistory : BaseEntity
{
public long InvId { get; set; }
public Inventory Inventory { get; set; }
public InvHistoryChangeType InvChangeType { get; set; }
public int InvChangeQuantity { get; set; }
public Employee Employee { get; set; }

}
В этой части я создавал ApplicationDbContext, чтобы связать весь необходимый внешний ключ с инвентарем.

Код: Выделить всё

    public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions options) : base(options)
{

}
public DbSet Inventory { get; set; }
public DbSet RestockRecord { get; set; }
public DbSet SaleRecord { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);

modelBuilder.Entity()
.HasOne(inventoryHistory => inventoryHistory.Inventory)
.WithMany(inventory => inventory.InventoryHistory)
.HasForeignKey(inventoryHistory => inventoryHistory.InvId);

modelBuilder.Entity()
.HasOne(inventoryHistory => inventoryHistory.Employee)
.WithMany(employee => employee.InventoryHistory)
.HasForeignKey(inventoryHistory => inventoryHistory.CreatedBy)
.OnDelete(DeleteBehavior.NoAction);

modelBuilder.Entity()
.HasOne(restockRecord => restockRecord.Inventory)
.WithMany(inventory => inventory.RestockRecord)
.HasForeignKey(restockRecord => restockRecord.InvId);

modelBuilder.Entity()
.HasOne(restockRecord => restockRecord.Employee)
.WithMany(employee => employee.RestockRecord)
.HasForeignKey(restockRecord => restockRecord.CreatedBy)
.OnDelete(DeleteBehavior.NoAction);
}
}
Затем я создаю InventoryController для API

Код: Выделить всё

[HttpPost]
[Route("Create")]
public async Task  CreateInventory([FromBody] InventoryCreateDto dto)
{
Inventory newInventory = _mapper.Map(dto);
await _context.Inventory.AddAsync(newInventory);
await _context.SaveChangesAsync();

return Ok("Inventory created!");
}
Это когда я зашел в пользовательский интерфейс Swagger, чтобы разместить данные, и там есть длинный список данных, которые необходимо вставить.

Код: Выделить всё

{
"invName": "string",
"invQuantity": 0,
"invPrice": 0,
"employee": {
"id": 0,
"createdAt": "2024-10-17T16:06:30.818Z",
"updatedAt": "2024-10-17T16:06:30.818Z",
"createdBy": 0,
"empName": "string",
"empContact": "string",
"empRole": "Manager",
"isActive": true,
"saleRecord": [
{
"id": 0,
"createdAt": "2024-10-17T16:06:30.818Z",
"updatedAt": "2024-10-17T16:06:30.818Z",
"createdBy": 0,
"saleQuantity": 0,
"invId": 0,
"inventory": {
"id": 0,
"createdAt": "2024-10-17T16:06:30.818Z",
"updatedAt": "2024-10-17T16:06:30.818Z",
"createdBy": 0,
"invName": "string",
"invQuantity": 0,
"invPrice": 0,
"employee": "string",
"inventoryHistory": [
"string"
],
"restockRecord": [
"string"
]
},
"billId": 0,
"bill": {
"id": 0,
"createdAt": "2024-10-17T16:06:30.818Z",
"updatedAt": "2024-10-17T16:06:30.818Z",
"createdBy": 0,
"billTotal": 0,
"cusId": 0,
"customer": {
"id": 0,
"createdAt": "2024-10-17T16:06:30.818Z",
"updatedAt": "2024-10-17T16:06:30.818Z",
"createdBy": 0,
"cusName": "string",
"cusContact": "string",
"bill": [
"string"
],
"employee": "string"
},
"saleRecord": [
"string"
],
"employee": "string"
},
"employee": "string"
}
],
"restockRecord": [
{
"id": 0,
"createdAt": "2024-10-17T16:06:30.818Z",
"updatedAt": "2024-10-17T16:06:30.818Z",
"createdBy": 0,
"invId": 0,
"inventory": {
"id": 0,
"createdAt": "2024-10-17T16:06:30.818Z",
"updatedAt": "2024-10-17T16:06:30.818Z",
"createdBy": 0,
"invName": "string",
"invQuantity": 0,
"invPrice": 0,
"employee": "string",
"inventoryHistory": [
"string"
],
"restockRecord": [
"string"
]
},
"restockQuantity": 0,
"employee": "string"
}
],
"bill": [
{
"id": 0,
"createdAt": "2024-10-17T16:06:30.818Z",
"updatedAt": "2024-10-17T16:06:30.818Z",
"createdBy": 0,
"billTotal": 0,
"cusId": 0,
"customer": {
"id": 0,
"createdAt": "2024-10-17T16:06:30.818Z",
"updatedAt": "2024-10-17T16:06:30.818Z",
"createdBy": 0,
"cusName":  "string",
"cusContact": "string",
"bill": [
"string"
],
"employee": "string"
},
"saleRecord": [
"string"
],
"employee": "string"
}
],
"inventoryHistory": [
{
"id": 0,
"createdAt": "2024-10-17T16:06:30.818Z",
"updatedAt": "2024-10-17T16:06:30.818Z",
"createdBy": 0,
"invId": 0,
"inventory": {
"id": 0,
"createdAt": "2024-10-17T16:06:30.818Z",
"updatedAt": "2024-10-17T16:06:30.818Z",
"createdBy": 0,
"invName": "string",
"invQuantity": 0,
"invPrice": 0,
"employee": "string",
"inventoryHistory": [
"string"
],
"restockRecord": [
"string"
]
},
"invChangeType": "Sales",
"invChangeQuantity": 0,
"employee": "string"
}
],
"inventory": [
{
"id": 0,
"createdAt": "2024-10-17T16:06:30.818Z",
"updatedAt": "2024-10-17T16:06:30.818Z",
"createdBy": 0,
"invName": "string",
"invQuantity": 0,
"invPrice": 0,
"employee": "string",
"inventoryHistory": [
"string"
],
"restockRecord": [
"string"
]
}
],
"customer": [
{
"id": 0,
"createdAt": "2024-10-17T16:06:30.818Z",
"updatedAt": "2024-10-17T16:06:30.818Z",
"createdBy": 0,
"cusName": "string",
"cusContact": "string",
"bill": [
"string"
],
"employee": "string"
}
]
}
}
Для справки: это таблица базы данных таблицы инвентаризации.

Код: Выделить всё

SELECT TOP (1000) [ID]
,[InvName]
,[InvQuantity]
,[InvPrice]
,[CreatedAt]
,[UpdatedAt]
,[CreatedBy]
FROM [StoreManagementSystem].[dbo].[Inventory]

Я пытался добавить внешний ключ в инвентарь, возможно, поэтому теперь требуется так много других избыточных данных, и надеялся запросить только invName, invQuantity, InvPrice, CreatedAt, UpdatedAt, CreatedBy (идентификатор сотрудника) за создание Post API.
Заранее благодарим за предоставленную помощь.

Подробнее здесь: https://stackoverflow.com/questions/790 ... -much-info
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»