我有两个模型,Fish
和Place
。
位置: 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
。模特吗?