gpt4 book ai didi

c# - 系统.Data.SqlClient.SqlException : Column name or number of supplied values does not match table definition

转载 作者:行者123 更新时间:2023-11-30 17:36:45 24 4
gpt4 key购买 nike

我希望用户输入显示的所有数据(数据库中的列),填写并提交。我无法使用 HTML.HiddenFor 元素自动生成 Id 和 CompanyID。

System.Data.SqlClient.SqlException: Column name or number of supplied values does not match table definition..

型号:

namespace Project.Models
{
public class Contact
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public int Phone { get; set; }
public int CompanyID { get; set; }
}
}

查看:

@model Project.Contact

<h2>Create Contact</h2>

@using (Html.BeginForm("Create", "Home", FormMethod.Post))
{
<table>
<tr>
<th>First name</th>
<th>Last name</th>
<th>Email</th>
<th>Phone</th>
</tr>
<tr>
<td>@Html.HiddenFor(m => m.Id)</td>
<td></td>
<td>@Html.TextBoxFor(m => m.FirstName)</td>
<td>@Html.TextBoxFor(m => m.LastName)</td>
<td>@Html.TextBoxFor(m => m.Email)</td>
<td>@Html.TextBoxFor(m => m.Phone)</td>
<td>@Html.HiddenFor(m => m.CompanyID)</td>
</tr>

</table>
<br />
<input type="submit" name="btn" class="btn-primary" value="Create" />
}

Controller :

using Arbetsprov_Sublime___Andre_Kordasti.Models;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web.Mvc;

namespace Arbetsprov_Sublime___Andre_Kordasti.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}

[HttpGet]
public ActionResult Create()
{
return View();
}

[HttpPost]
public ActionResult Create(Contact model)
{
var connection = new SqlConnection(@"Data Source=.\SQLExpress;Initial Catalog=Sublime;Integrated Security=True");
connection.Open();

var command = new SqlCommand("INSERT INTO Contact Values('" + model.Id + "','" + model.FirstName + " " + model.LastName + "','" + model.Email + " " + model.Phone + "','" + model.CompanyID + "')", connection);
command.ExecuteNonQuery();

return View();
}
}
}

最佳答案

var command = new SqlCommand("INSERT INTO Contact(Id,FirstName,LastName,Email,Phone,CompanyId) Values('" + model.Id + "','" + model.FirstName + " " + model.LastName + "','" + model.Email + " " + model.Phone + "','" + model.CompanyID + "')", connection);
command.ExecuteNonQuery();

如果有一列必须自动生成,你必须告诉你为哪一列提供的值,以便 sql 知道没有提到的属性应该自动生成

关于c# - 系统.Data.SqlClient.SqlException : Column name or number of supplied values does not match table definition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39052387/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com