C# 脚手架API控制器是不同的
我有两种型号,C# 脚手架API控制器是不同的,c#,asp.net-mvc,asp.net-core,asp.net-core-scaffolding,C#,Asp.net Mvc,Asp.net Core,Asp.net Core Scaffolding,我有两种型号,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
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; }
FishController:
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);
}
public异步任务PostFish([FromBody]Fish)
{
_context.Fish.Add(Fish);
wait_context.SaveChangesAsync();
返回CreateDataAction(“GetFish”,新的{id=fish.FishId},fish);
}
是否由于数据库未设置PK,Place
的脚手架方法对重复项进行额外控制
我还将数据库中的
Name
属性设置为UNIQUE,因此我认为如果EF检查用户输入中唯一的列,它可能也应该检查Fish
模型中的Name
?如果您想检查模型中的UNIQUE,可以参考。使用[Key]
属性,或在构建模型时将其定义为键
。谢谢@SalehBagheri