从继承自另一个 class 的 class 获取数据

Getting data from a class that inherits from another class

我一直在使用 asp.net Core 3 开发图书馆管理网站 API。我有一个名为 LibraryAsset 的基础 class 和另一个名为 Book 的 class,图书 class 继承自 LibraryAsset class。我使用 EF 核心 CF 工作流构建我的数据库,并为具有鉴别器列的 LibraryAsset 创建了数据 table。

我 运行 在 API 上进行测试以获取所有库资产,它 returns 库资产但是缺少一些属性。这些属性在书籍 class 中。使用 API 调用时,如何将这些属性添加到库资源中?

这是Book.cs Class:

public class Book: LibraryAsset
    {
        public string ISBN { get; set; } 
        [Required]
        [StringLength(255)]
        public string Author { get; set; }
    }

虽然这是 LibraryAsset Class

public class LibraryAsset
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public int YearPublished { get; set; }
        public float Cost { get; set; }
    }

这是我测试 API

时得到的结果
{
    "id": 1,
    "title": "Children of Blood and Bone",
    "yearPublished": 2018,
    "cost": 8000
}

这是 API 的 Get 函数:

public async Task<IEnumerable<LibraryAsset>> GetAllAssets() {
      return await _context.LibraryAssets.ToListAsync();
}

您可以直接使用 JsonConvert.SerializeObject 来 return 您的 JSON:

using Newtonsoft.Json;

public async Task<string> GetAllAssets() {
   return JsonConvert.SerializeObject(await _context.LibraryAssets.ToListAsync());
}

或者您可以将签名更改为 return a Task<JsonResult> 并执行 return new JsonResult(await _context.LibraryAssets.ToListAsync());

have a base class called LibraryAsset and another class called Book, the Book class inherits from the LibraryAsset class. I build my database with EF core CF workflow and a data table was created for the LibraryAsset that has a discriminator column.

ran a test on the API to get all library assets, it returns the library asset however some properties are missing.

如果你想得到所有的书,你可以尝试:

await _context.Books.ToListAsync();

如果您想从数据库中获取所有资产 table LibraryAsset,您可以尝试:

public async Task<IActionResult> GetAllAssets()
{    
    using (var command = _context.Database.GetDbConnection().CreateCommand())
    {
        command.CommandText = "SELECT Id, Title, YearPublished, Cost, Discriminator, ISBN, Author FROM dbo.LibraryAsset";
        _context.Database.OpenConnection();

        using (var myDataReader = command.ExecuteReader())
        {
            var dt = new DataTable();
            dt.Load(myDataReader);

            var allAssets = dt.AsEnumerable().Select(s => new
            {
                Id = s.Field<int>("Id"),
                Title = s.Field<string>("Title"),
                YearPublished = s.Field<int>("YearPublished"),
                Cost = s.Field<float>("Cost"),
                ISBN = s.Field<string>("ISBN"),
                Author = s.Field<string>("Author")
            }).ToList();

            return Ok(allAssets);
        }
    }
}