简体   繁体   English

ASP.NET Core 3.1 和 Entity Framework Core:一对多的关系

[英]ASP.NET Core 3.1 and Entity Framework Core : one-to-many relationship

I am new to Entity Framework Core 3.1 and ASP.NET Core 3.1 in general.一般来说,我是 Entity Framework Core 3.1 和 ASP.NET Core 3.1 的新手。 What I am trying to do is set up my tables Categories , Manufacturers , Conditions , Locations and AssetFiles to have a one-to-many relationship with my Asset table.我要做的是设置我的表CategoriesManufacturersConditionsLocationsAssetFiles与我的Asset表建立一对多的关系。

These are the data models that I have currently这些是我目前拥有的数据模型

The Asset table Asset

public class Asset
{
        public int Id { get; set; }
        public Categories Category { get; set; }
        public Manufacturers Manufacturer { get; set; }
        public string Model { get; set; }
        public string SerialNumber { get; set; }
        public string PurchasePlace { get; set; }
        public int Quantity { get; set; }
        public DateTime AcquiredDate { get; set; }
        public string PurchasePrice { get; set; } 
        public string CurrentValue { get; set; }
        public Conditions Condition { get; set; }
        public Locations Location { get; set; }
        public AssetFiles Files { get; set; }
} 

Categories table Categories

public class Categories
{
        public int Id { get; set; }
        public string CategoryName { get; set; }
        public ICollection<Asset> Assets { get; set; }
}

The other tables have pretty much the same format.其他表格的格式几乎相同。 I can create the migration and update the database so that it is created.我可以创建迁移并更新数据库以便创建它。 It looks to me like it is working the way that I want it to.在我看来,它正在按照我想要的方式工作。

My question is how do I access these tables in my Assets controller in the [HttpPost] method to be able to add a category, manufacturer, condition, Location, to the Asset when it is posted cause right now With the controller scaffolded all I'm getting is null for those sections of my asset我的问题是如何在[HttpPost]方法中访问我的资产 controller 中的这些表,以便能够在资产发布时向Asset添加类别、制造商、条件、位置,因为现在使用 controller 搭建了所有我的脚手架对于我的资产的这些部分,我得到的是 null

Here is my post method of my assetController :这是我的assetController的 post 方法:

[HttpPost]
public async Task<ActionResult<Asset>> PostAsset([FromForm] Asset asset)
{
        _context.Assets.Add(asset);
        await _context.SaveChangesAsync();

        return CreatedAtAction("GetAsset", new { id = asset.Id }, asset);
}

I'm just looking for a little direction on how I need to look at this to move forward.我只是在寻找一个关于我需要如何看待这个向前发展的小方向。

Any help would be appreciated.任何帮助,将不胜感激。

postman submission/result postman 提交/结果在此处输入图像描述

Edit: 2编辑:2

Also just to mention I am using a VueJs Front End not sure if that matters to the tips you are giving or if accessing the data is the same.还要提一下,我正在使用 VueJs 前端,不确定这对您提供的提示是否重要,或者访问数据是否相同。

Your string values: Tool, Ikea etc. will not be magically converted into C# objects.您的字符串值:Tool、Ikea 等不会被神奇地转换为 C# 对象。 If you want to pass object with Form Data you can make POST in postman like this:如果你想通过表单数据传递 object,你可以像这样在 postman 中进行 POST:

邮政

This initialize your Category object with Id=0 and Name= "Tool".这将初始化您的类别 object,Id=0 和 Name=“工具”。 This solution is proper if you want to create new category with your request and id will be assigned by database engine (most common way).如果您想使用您的请求创建新类别并且 id 将由数据库引擎分配(最常见的方式),则此解决方案是合适的。

But I suppose that you want to use existing category when creating Asset.但我想您想在创建资产时使用现有类别。 You'd better create another endpoint: POST /api/categories .您最好创建另一个端点: POST /api/categories The endpoint should return you new category with database cateogry id.端点应返回带有数据库类别 ID 的新类别。 The Category id could be used in POST /asset request.类别 ID 可用于POST /asset请求。

Your API controller should not has EF entity as parameter.您的 API controller 不应将 EF 实体作为参数。 Instead use ViewModel :而是使用ViewModel

 public class AssetViewModel
 {
    public int CategoryId { get; set; }
    public int ManufacturerId { get; set; }
    public string Model { get; set; }
    public string SerialNumber { get; set; }
    public string PurchasePlace { get; set; }
    public int Quantity { get; set; }
    public DateTime AcquiredDate { get; set; }
    public string PurchasePrice { get; set; } 
    public string CurrentValue { get; set; }
    public int ConditionId { get; set; }
    public int LocationId { get; set; }
    public int AssetFilesId { get; set; }

} }

In your controller you should check if category with CategoryId exists in database.在您的 controller 中,您应该检查数据库中是否存在具有 CategoryId 的类别。 If not return NotFound or BadRequest .如果不返回NotFoundBadRequest

You could also want to create eg AssetFiles in the same request.您可能还想在同一个请求中创建例如 AssetFiles。 Instead of property int AssetFilesId , you could use AssetFileViewModel and POST it as above.而不是属性int AssetFilesId ,您可以使用AssetFileViewModel并如上所述发布它。

 public class AssetViewModel
 {
    public int CategoryId { get; set; }
    ...
    public AssetFileViewModel AssetFile { get; set; }
}
public class AssetFileViewModel
{
    public string Name { get; set; }
    public string SomeOtherProperty { get; set; }
}

At the end you can create your Asset from ViewModel and save it to database.最后,您可以从 ViewModel 创建资产并将其保存到数据库。

Are you sure that you want to use Form Data Body.您确定要使用表单数据体。 The most common way is to use JSON (in postman choose Body -> Raw -> JSON)最常见的方法是使用 JSON (在 postman 中选择 Body -> Raw -> JSON)

It is a Form Data model binding problem.这是表单数据 model 绑定问题。 To bind the nested objects to the model, you need to specify the properties' name of the child object, and name it in the format ModelName.PropertyName.要将嵌套对象绑定到 model,您需要指定子 object 的属性名称,并以 ModelName.PropertyName 格式命名。

Take Category as an example, if you want to bind its Id and Name, you should write like this: Category.Id = 1 , Category.CategoryName = "Tool" .以 Category 为例,如果要绑定它的 Id 和 Name,应该这样写: Category.Id = 1 , Category.CategoryName = "Tool"

For more details about model binding, you can refer to the document关于model绑定的更多细节,可以参考文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将具有一对多关系的 SQL 查询转换为具有父/子 object 结构的 ASP.NET 核心/实体框架核心调用 - Convert SQL query with a one-to-many relationship to an ASP.NET Core / Entity Framework Core call with a parent/children object structure 实体框架核心,一对多关系,集合始终为空 - Entity Framework Core, one-to-many relationship, collection always empty 在 Entity Framework Core 中保存一对多关系 - Saving one-to-many relationship in Entity Framework Core ASP.NET CORE 3.1 中通过存储库模式的多对多关系 - Many to Many relationship in ASP.NET CORE 3.1 by repository pattern ASP.NET MVC3和实体框架 - 一个视图中的一对多关系 - ASP.NET MVC3 and Entity Framework- one-to-many relationship in one view ASP.Net实体框架一对多关系:如何建立依赖关系和延迟加载不起作用 - ASP.Net Entity Framework one-to-many relationship: How to establish dependency and lazy loading not working ASP.NET Core中如何将一对多的关系数据添加到数据库中? - How to add one-to-many relationship data to the database in ASP.NET Core? asp.Net Core 一对多关系 UPDATE 语句与 FOREIGN KEY 约束冲突 - asp.Net Core one-to-many relationship UPDATE statement conflicted with the FOREIGN KEY constraint Entity Framework Core:一对多关系 - Entity Framework Core : one-to-many relationships ASP.NET 3.1 Web API,实体框架一对多关系要么没有建立要么以循环结束 - ASP.NET 3.1 Web API, Entity Framework one to many relationship either not made or ending in cycle
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM