【问题标题】:Getting Json object as View Model from ajax call & insert that using Entity Framework Core从ajax调用获取Json对象作为视图模型并使用Entity Framework Core插入
【发布时间】:2021-03-17 21:03:06
【问题描述】:

我使用以下代码从 Ajax 获取视图模型数据:

  $.ajax({
            url: '@Url.Action("Create", "Invoice")',
            type: "POST",
            contentType: 'application/json',
            data: JSON.stringify(invoiceViewModel),
            success: function (response) {
                alert(response + " records inserted.")
            },
            error: function (response) {
                alert(response + " records not inserted.")
            }
        });

然后我想将它插入到我的控制器中的 Create 操作中。

如何使用 Entity Framework Core 插入?

【问题讨论】:

  • How can I insert using Entity Framework Core? 您是否创建了所需的模型类、数据库上下文类并使用依赖注入注册了您的数据库上下文?要开始在 ASP.NET MVC 中使用 EF Core,请查看此文档:docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/…
  • 嗨@Ager,有关于这个案例的最新消息吗?

标签: ajax entity-framework-core asp.net-core-mvc


【解决方案1】:

我想将它插入到我的控制器中的 Create 操作中。如何使用 Entity Framework Core 插入?

首先,您可能需要创建数据模型和数据库上下文类,并在应用程序启动期间将您的数据库上下文注册为服务。

services.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

有关在 ASP.NET MVC 中使用 EF Core 的更多信息,请参阅this doc about "get started with EF Core in an ASP.NET MVC"

注意:如果您已经创建了相应的模型类并注册了所需的服务,请跳过此步骤。

在 MVC 项目中设置 EF Core 后,可以通过构造函数注入在控制器(或其他服务)中使用 DbContext。

public class InvoiceController : Controller
{
    private readonly MyDbContext _context;

    public InvoiceController(MyDbContext context)
    {
        _context = context;
    }

并使用以下代码sn-p将新记录添加到数据库。

if (ModelState.IsValid)
{
    _context.Add(invoice);
    await _context.SaveChangesAsync();
}

此外,为了保护您的控制器免于过度发布,请only include properties in the [Bind] attribute您要更改。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-08
    • 2016-06-30
    • 1970-01-01
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    相关资源
    最近更新 更多