我有两个模型,Fish
和Place
.
Place: Coord
作为主键,由用户设置。
public Place()
[Required]
public string Coord { get; set; }
[Required]
public string Name { get; set; }
Fish: FishId
作为主键,由数据库设置,具有标识。
public Fish()
{
Habitats = new HashSet<Habitat>();
}
public int FishId { get; set; }
[Required]
public string Species { get; set; }
当我为这些实体搭建 API 控制器时,POST
操作的工作方式会有所不同。
地点控制器:
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);
}
鱼控制器:
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
模型中检查?