在MVC5 c#EF中生成和存储GUID值

时间:2018-06-13 15:20:55

标签: c# asp.net-mvc guid

我会在此感谢一些帮助。我正在尝试使用MVC 5 EF创建一个ASP.NET Web应用程序。我已经搭建了我的模型以生成视图和控制器,显然创建按钮/插入按钮没有响应(不会将值插入数据库,但我可以直接在数据库接口上插入值)。我怀疑它与我用作主键的GUID值有关。

这是我的代码 的模型

public class Supplier
{

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid SupplierId { get; set; }
    [Required]
    [Display(Name = "Supplier Name")]
    [StringLength(100, ErrorMessage = "Name cannot be longer than 30 characters.")]
    [Remote("doesSupplierExist", "Supplier", HttpMethod = "POST", ErrorMessage = "Duplicate Supplier Name Detected")]
    public string Name { get; set; }
    [Required]
    [Display(Name = "Supplier phone Number")]
    public int Phone { get; set; }
    [Required]
    [Display(Name = "Supplier Email")]
    [StringLength(100, ErrorMessage = "Email cannot be longer than 50 characters.")]
    public string Email { get; set; }
    [Required]
    [Display(Name = "Supplier Location")]
    [StringLength(100, ErrorMessage = "Location cannot be longer than 50 characters.")]
    public string Location { get; set; }

}

控制器

public class SuppliersController : Controller
{
   private ApplicationDbContext db = new ApplicationDbContext();

    // GET: Suppliers
    public async Task<ActionResult> Index()
    {
        return View(await db.Suppliers.ToListAsync());
    }

    // GET: Suppliers/Details/5
    public async Task<ActionResult> Details(Guid? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Supplier supplier = await db.Suppliers.FindAsync(id);
        if (supplier == null)
        {
            return HttpNotFound();
        }
        return View(supplier);
    }

    // GET: Suppliers/Create
    public ActionResult Create()
    {
        return View();
    }

    // POST: Suppliers/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Create([Bind(Include ="SupplierId,Name,Phone,Email,Location")] Supplier supplier)
    {
        if (ModelState.IsValid)
        {
            supplier.SupplierId = Guid.NewGuid();
            db.Suppliers.Add(supplier);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        return View("Index");
    }

    // GET: Suppliers/Edit/5
    public async Task<ActionResult> Edit(Guid? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Supplier supplier = await db.Suppliers.FindAsync(id);
        if (supplier == null)
        {
            return HttpNotFound();
        }
        return View(supplier);
    }

    // POST: Suppliers/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Edit([Bind(Include = "SupplierId,Name,Phone,Email,Location")] Supplier supplier)
    {
        if (ModelState.IsValid)
        {
            db.Entry(supplier).State = EntityState.Modified;
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }
        return View(supplier);
    }

    // GET: Suppliers/Delete/5
    public async Task<ActionResult> Delete(Guid? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Supplier supplier = await db.Suppliers.FindAsync(id);
        if (supplier == null)
        {
            return HttpNotFound();
        }
        return View(supplier);
    }

    // POST: Suppliers/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> DeleteConfirmed(Guid id)
    {
        Supplier supplier = await db.Suppliers.FindAsync(id);
        db.Suppliers.Remove(supplier);
        await db.SaveChangesAsync();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}

创建视图

@{
  ViewBag.Title = "Create";
  Layout = "~/Views/Shared/_dashboardLayout.cshtml";
 }
  <h2>Create</h2>

 @using (Html.BeginForm()) 
  {
   @Html.AntiForgeryToken()


<div class="form-horizontal">
    <h4>Supplier</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Phone, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Phone, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Location, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Location, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Location, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>

<div>
@Html.ActionLink("Back to List", "Index")
</div>

移植

CreateTable("dbo.Suppliers",
            c => new
                {
                    SupplierId = c.Guid(nullable: false, identity: true, 
                    defaultValueSql: "newsequentialid()"),
                    Name = c.String(nullable: false, maxLength: 100),
                    Phone = c.Int(nullable: false),
                    Email = c.String(nullable: false, maxLength: 100),
                    Location = c.String(nullable: false, maxLength: 100),
                })
            .PrimaryKey(t => t.SupplierId);

1 个答案:

答案 0 :(得分:0)

您需要从主键中删除以下属性。

DatabaseGenerated(DatabaseGeneratedOption.Identity)

您提供了一个价值,您不需要数据库为您生成一个。此外,据我所知,您不能将GUID(SQL中的uniqueidentifier)作为标识列。