嗨,我想直接从我的控制器添加模型数据,而不实现任何其他。
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;
}
您可以执行以下操作:
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"]),
}
}
}