EFcore从控制器向db添加数据

问题描述 投票:0回答:1

嗨,我想直接从我的控制器添加模型数据,而不实现任何其他。

namespace WebApplication3.Controllers
{

    public class ApiController : Controller
    {
        readonly HumanDBContext _humanContext;

...我希望能够直接从db获取数据:

   [HttpGet]
        public JsonResult Godaddy()
        {

--fix在这里:

   public class ApiController : Controller
    {        private readonly HumanDBContext _db;

 public ApiController(IUserService userService,HumanDBContext db)
    {
        _db = db;
        _userService = userService;
    }
.net entity-framework
1个回答
0
投票

您可以执行以下操作:

public jsonResult Get()
{
  DbCommand cmd = _humanContext.DbContext.Database.GetDbConnection().CreateCommand()
 cmd.CommandText = "yourspName";
 cmd.CommandType = CommandType.StoredProcedure;


using (IDataReader reader = await cmd.ExecuteReaderAsync())
{
 List<Foo> items= reader.Select(r => r.GetYourPocoClassModel()).ToList();

string rItems = JsonConvert.SerializeObject(items, Formatting.Indented,
   new JsonSerializerSettings
   {
       ReferenceLoopHandling = ReferenceLoopHandling.Ignore
    });
 return rItems;
 }
}

和GetYourPocoClassModel用于建模您的数据:

public Calss HelperExtension
{
   public static Foo GetYourPocoClassModel(this IDataReader r)
   {
    return new Foo
    {
      Id=r["Id"] is DBNull ? 0 : Convert.ToDouble(r["Id"]),
    }
 }
}
© www.soinside.com 2019 - 2024. All rights reserved.