脚手架API控制器不同

时间:2020-11-11 21:13:15

标签: c# asp.net-mvc asp.net-core asp.net-core-scaffolding

我有两个模型,FishPlace

位置: Coord充当主键,由用户设置。

public Place()

[Required]
public string Coord { get; set; }

[Required]
public string Name { get; set; }

鱼: FishId充当主键,并由具有标识的数据库设置。

public Fish()
{
    Habitats = new HashSet<Habitat>();
}

public int FishId { get; set; }

[Required]
public string Species { get; set; }

当我为这些实体使用API​​控制器时,POST操作的工作方式会有所不同。

PlacesController:

public async Task<ActionResult<Place>> PostPlace([FromBody]Place place)
{
    _context.Places.Add(place);
    try
    {
        await _context.SaveChangesAsync();
    }
    catch (DbUpdateException)
    {
        if (PlaceExists(place.Coord))
        {
            return Conflict();
        }
        else
        {
            throw;
        }
    }
    return CreatedAtAction("GetPlace", new { id = place.Coord }, place);
}

FishController:

public async Task<ActionResult<Fish>> PostFish([FromBody]Fish fish)
{
    _context.Fish.Add(fish);
    await _context.SaveChangesAsync();

    return CreatedAtAction("GetFish", new { id = fish.FishId }, fish);
}

是否由于数据库未设置PK而Place的脚手架方法对重复项进行了额外控制?

我还在数据库中将Name属性设置为UNIQUE,所以我认为,如果EF检查用户输入中唯一的列,则它应该检查Name中的Fish。模特吗?

0 个答案:

没有答案