【问题标题】:How to make a single form that will send data to multiple table in Microsoft SQL server ? ASP.Net如何制作一个将数据发送到 Microsoft SQL Server 中的多个表的表单? ASP.NET
【发布时间】:2019-05-16 06:03:48
【问题描述】:

我通过使用 ASP.net 核心 MVC 中的模型迁移在 SQL 服务器中创建了名为 Model.User 和 Model.Company 的这两个表之间的一对一关系。我不知道如何使用这个单一的 View.User 将数据插入到这两个表中

public class User
{
    [Key]
    [Display(Name = "User ID")]
    [DataType(DataType.EmailAddress)]
    public string UserID { get; set; }

    public string UserName { get; set; }

    [Display(Name = "Phone Number")]
    [DataType(DataType.PhoneNumber)]
    public string PhoneNumber { get; set; }

    [DataType(DataType.Password)]
    [MinLength(6, ErrorMessage = "Minimum 6 characters required")]
    public string Password { get; set; }

    public virtual Company Company { get; set; }
}



public class Company
{
    [ForeignKey("User")]
    [Display(Name = "Company ID")]
    [Required(AllowEmptyStrings = false, ErrorMessage = "Company number required")]
    public string CompanyID { get; set; }

    [Display(Name = "Company Name")]
    [Required(AllowEmptyStrings = false, ErrorMessage = "Company name required")]
    public string CompanyName { get; set; }

    [Display(Name = "Company Address")]
    [Required(AllowEmptyStrings = false, ErrorMessage = "Company address required")]
    public string CompanyAddress { get; set; }

    public virtual User User { get; set; }
}

public IActionResult Create()
    {
        return View();
    }

    // POST: Users/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("UserID,UserName,PhoneNumber,Password,CompanyID,CompanyName,CompanyAddress")] User user)
    {
        if (ModelState.IsValid)
        {
            _context.Add(user);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(user);
    }

【问题讨论】:

  • 欢迎来到stackoverflow。请花一分钟时间回答tour,尤其是How to Ask,以及edit您的问题。
  • 如果您向我们展示您正在尝试执行的代码,这将有助于理解您的问题以及控制器代码和您创建的类。

标签: c# asp.net-core model-view-controller


【解决方案1】:

首先创建一个包含两个模型的自定义模型。喜欢

public class mainModel
{
   public User userModel{get; set;}
   public Company companyModel{get; set;}
}

然后在你的视图中声明这个模型,这样你就可以在你的视图中使用 mainModel 来使用这两个模型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-10
    • 1970-01-01
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    相关资源
    最近更新 更多