2

API와 웹을 모두 포함하는 MVC Core 1.0.1 프로젝트를 만들고 있습니다. 그래서 내 모델을 만들었고 이제 각 모델을 스캐 폴딩하는 대신 단일 컨트롤러 내에서 CRUD 작업을 만들고 싶습니다. 나는이모든 모델을 제어하는 ​​하나의 웹 API 컨트롤러

[Consumes("application/json")] 
[Produces("application/json")] 
[Route("/api/{resource}")] 
public class ApiController : Controller 
{ 
    private readonly MasterContext _context; 

    public ApiController(MasterContext context) 
    { 
     _context = context; 
    } 

    [HttpPost] 
    public IActionResult Create(string resource, [FromBody] object body) 
    { 
     //_context.Add(); 
     return Ok("ok api Create"); 

    } 

    [HttpGet("{id?}")] 
    public IActionResult Read(string resource, int? id) 
    { 
     return Ok("ok api get Read"); 
    } 
    [HttpPatch("{id}")] 
    public IActionResult Update(string resource, [FromBody] object body) 
    { 
     //_context.Update(); 
     return Ok("ok api Update"); 
    } 
    [HttpDelete("{id}")] 
    public IActionResult Delete(string resource, [FromBody] object body) 
    { 
     return Ok("ok api Delete"); 
    } 
} 

처럼 내가 (포스트, 가져 오기, 패치, 삭제)해야하는 각 HTTP 방법에 대한 방법이이 방법을 보이는 ApiController를 생성 한 자원에 내가 문자열로 모델을 가지고 본문에는 요청의 본문이 객체로 있습니다. 요청한 작업을 수행하기 위해 엔터티 프레임 워크를 사용하기 전에 리소스에 따라 모델을 찾아서 해당 본문을 해당 클래스로 변환해야합니다.

어떻게해야할까요? 동료가 Python을 사용하여이 작업을 수행했습니다. C#을 사용하여 수행 할 수 있으며 결과에 어떤 단점이 있습니까? 예를 들어, 나는 모델 검증이 어렵다고 생각합니다.

답변

1

예, 가능합니다. 이제 우리는이 DbContext 있다고 가정 해 봅시다 :

public partial class FooContext : DbContext 
{ 
    //has "MyAssembly.Blog" type 
    public virtual DbSet<Blog> Blog { get; set; } 
}   

은 우리가 처음 Blog 유형을 찾아야한다 데이터베이스에 새 개체를 저장합니다.

//you called POST /blog 
string resource = "blog"; 
string body = "{...}"; 

var context = new FooContext(); 

IEntityType entityType = context.Model 
    .GetEntityTypes() 
    .First(x => x.Name.EndsWith($".{resource}", StringComparison.OrdinalIgnoreCase)); 

//This type should be "MyAssembly.Blog" - exact entity CLR type. 
//Another option to get this CLR type is assembly scan. 
Type type = entityType.ClrType; 

//having type, it is possible to create instance 
object entity = JsonConvert.DeserializeObject("body", type); 
//var entity = Activator.CreateInstance(type); 

context.Entry(entity).State = EntityState.Added; 
context.SaveChanges(); 

데이터베이스에서 ID로 엔티티를 읽으려면, 제네릭이 아닌 DbContext.Find

var entityFromDb = context.Find(type, id); 

P.S.을 사용 유형을 갖는,이 객체를 직렬화하고 저장하는 것은 쉽다 일반 ApiController은 일반적으로 좋지 않은 생각입니다. 그것은 부피가 크며 불필요한 복잡성은 있지만 엄청난 이점을 가져옵니다.

+0

답장을 보내 주셔서 감사합니다. Context.Find가 존재하지 않습니다.이 방법을 만들었습니까? 모든 팁 만드는 방법 이드에 의해 찾을 수 있습니까? –

+0

@DimitrisLaliotis,'Find'는 내장 된 메소드입니다. https://github.com/aspnet/EntityFramework/blob/dev/src/EFCore/DbContext.cs#L1138 최신 EF 핵심 패키지가 있는지 확인하십시오. –