在.NET Core中创建一个带有两个外部ID键的模型类和控制器,可以按照以下步骤进行:
public class MyModel
{
public int Id { get; set; }
public int ExternalId1 { get; set; }
public int ExternalId2 { get; set; }
// 其他属性
}
[Route("api/[controller]")]
[ApiController]
public class MyModelsController : ControllerBase
{
private readonly MyDbContext _context;
public MyModelsController(MyDbContext context)
{
_context = context;
}
// GET: api/MyModels
[HttpGet]
public async Task<ActionResult<IEnumerable<MyModel>>> GetMyModels()
{
return await _context.MyModels.ToListAsync();
}
// GET: api/MyModels/5
[HttpGet("{id}")]
public async Task<ActionResult<MyModel>> GetMyModel(int id)
{
var myModel = await _context.MyModels.FindAsync(id);
if (myModel == null)
{
return NotFound();
}
return myModel;
}
// POST: api/MyModels
[HttpPost]
public async Task<ActionResult<MyModel>> PostMyModel(MyModel myModel)
{
_context.MyModels.Add(myModel);
await _context.SaveChangesAsync();
return CreatedAtAction("GetMyModel", new { id = myModel.Id }, myModel);
}
// PUT: api/MyModels/5
[HttpPut("{id}")]
public async Task<IActionResult> PutMyModel(int id, MyModel myModel)
{
if (id != myModel.Id)
{
return BadRequest();
}
_context.Entry(myModel).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!MyModelExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// DELETE: api/MyModels/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteMyModel(int id)
{
var myModel = await _context.MyModels.FindAsync(id);
if (myModel == null)
{
return NotFound();
}
_context.MyModels.Remove(myModel);
await _context.SaveChangesAsync();
return NoContent();
}
private bool MyModelExists(int id)
{
return _context.MyModels.Any(e => e.Id == id);
}
}
请注意,上述代码中的MyDbContext
是指代你的数据库上下文类,你需要根据自己的数据库设置进行相应的更改。
这是一个简单的示例,你可以根据自己的需求进行修改和扩展。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云