主键mvc entitityframework模型错误

时间:2014-06-16 13:02:50

标签: c# sql asp.net-mvc entity-framework ef-database-first

这让我疯狂。

我有一个包含多个列和一个主键(bigint,not null)的表

我有VS创建它的模型

public long ParcelRangeID { get; set; }
..
..

然后我创建了Controller和View。当我使用“创建视图”创建新记录时,在db.SaveChanges上会出现问题:(我已将视图中的字段包含在HiddenFor中)

  • 没有进一步的变化;我得到一个必需的ID丢失错误。 (当我使用DataAnnotations [Key][DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)][HiddenInput(DisplayValue = false)]
  • 当我使用[Bind(Exclude="ParcelRangeID")]时,我得到了DbUpdateConcurrencyException。

如何插入新记录并自动生成所需的ID而不会出现错误?

修改

这是控制器代码:

    [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Create(ParcelRange parcelrange)
            {
                if (ModelState.IsValid)
                {
                    db.ParcelRange.Add(parcelrange);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }

                return View(parcelrange);
            }

模特:

 public partial class ParcelRange
    {
        public ParcelRange()
        {
            this.PickupAddressID = -1;
            this.OrganizationID = -1;
            this.DepotID = -1;
            this.IsVTG = 0;
            this.IsInternal = 0;
            this.IsInterCompany = 0;
            this.UpdateCount = 0;
            this.IsActive = 1;
            this.Modified = DateTime.Now.Date;
            this.Created = DateTime.Now.Date;
            this.ValidFrom = DateTime.Now.Date;
            this.ValidTo = DateTime.MaxValue;
        }

        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        [Key]
        [HiddenInput(DisplayValue = false)]
        public long ParcelRangeID { get; set; }
        public long NdswCustomerID { get; set; }
        public long PickupAddressID { get; set; }
        public long OrganizationID { get; set; }
        public long DepotID { get; set; }
        public string ParcelRangePrefix { get; set; }
        public string ParcelNumberStart { get; set; }
        public string ParcelNumberEnd { get; set; }
        public byte IsVTG { get; set; }
        public byte IsInternal { get; set; }
        public byte IsInterCompany { get; set; }
        public byte[] RowVer { get; set; }
        public System.DateTime Created { get; set; }
        public System.DateTime Modified { get; set; }
        public int UpdateCount { get; set; }
        public System.DateTime ValidFrom { get; set; }
        public System.DateTime ValidTo { get; set; }
        public byte IsActive { get; set; }
    }

编辑(2)

最后(默认)视图自动生成

@model MvcApplication1.ParcelRange

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    @Html.HiddenFor(model => model.ParcelRangeID)

    <fieldset>
        <legend>ParcelRange</legend>

        <div class="editor-label">

            @Html.LabelFor(model => model.NdswCustomerID)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.NdswCustomerID)
            @Html.ValidationMessageFor(model => model.NdswCustomerID)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.PickupAddressID)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.PickupAddressID)
            @Html.ValidationMessageFor(model => model.PickupAddressID)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.OrganizationID)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.OrganizationID)
            @Html.ValidationMessageFor(model => model.OrganizationID)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.DepotID)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.DepotID)
            @Html.ValidationMessageFor(model => model.DepotID)
        </div>

@*        <div class="editor-label">
            @Html.LabelFor(model => model.ParcelRangePrefix)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ParcelRangePrefix)
            @Html.ValidationMessageFor(model => model.ParcelRangePrefix)
        </div>*@

        <div class="editor-label">
            @Html.LabelFor(model => model.ParcelNumberStart)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ParcelNumberStart)
            @Html.ValidationMessageFor(model => model.ParcelNumberStart)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ParcelNumberEnd)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ParcelNumberEnd)
            @Html.ValidationMessageFor(model => model.ParcelNumberEnd)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.IsVTG)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.IsVTG)
            @Html.ValidationMessageFor(model => model.IsVTG)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.IsInternal)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.IsInternal)
            @Html.ValidationMessageFor(model => model.IsInternal)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.IsInterCompany)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.IsInterCompany)
            @Html.ValidationMessageFor(model => model.IsInterCompany)
        </div>

@*        <div class="editor-label">
            @Html.LabelFor(model => model.Created)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Created)
            @Html.ValidationMessageFor(model => model.Created)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Modified)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Modified)
            @Html.ValidationMessageFor(model => model.Modified)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.UpdateCount)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.UpdateCount)
            @Html.ValidationMessageFor(model => model.UpdateCount)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ValidFrom)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ValidFrom)
            @Html.ValidationMessageFor(model => model.ValidFrom)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ValidTo)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ValidTo)
            @Html.ValidationMessageFor(model => model.ValidTo)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.IsActive)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.IsActive)
            @Html.ValidationMessageFor(model => model.IsActive)
        </div>*@

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

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

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

编辑(3) 表的数据库脚本:

USE [DPDCDB_ODS]
GO

/****** Object:  Table [dbo].[ParcelRange]    Script Date: 16-6-2014 15:50:40 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[ParcelRange](
    [ParcelRangeID] [bigint] IDENTITY(1,1) NOT NULL,
    [NdswCustomerID] [bigint] NOT NULL,
    [PickupAddressID] [bigint] NOT NULL,
    [OrganizationID] [bigint] NOT NULL,
    [DepotID] [bigint] NOT NULL,
    [ParcelRangePrefix]  AS (left([ParcelNumberStart],(4))),
    [ParcelNumberStart] [nvarchar](50) NOT NULL,
    [ParcelNumberEnd] [nvarchar](50) NOT NULL,
    [IsVTG] [tinyint] NOT NULL,
    [IsInternal] [tinyint] NOT NULL,
    [IsInterCompany] [tinyint] NOT NULL,
    [RowVer] [timestamp] NOT NULL,
    [Created] [datetime] NOT NULL,
    [Modified] [datetime] NOT NULL,
    [UpdateCount] [int] NOT NULL,
    [ValidFrom] [date] NOT NULL,
    [ValidTo] [date] NOT NULL,
    [IsActive] [tinyint] NOT NULL,
 CONSTRAINT [PK_ParcelRange] PRIMARY KEY CLUSTERED 
(
    [ParcelRangeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [DATA]
) ON [DATA]

GO

ALTER TABLE [dbo].[ParcelRange] ADD  DEFAULT ((-1)) FOR [NdswCustomerID]
GO

ALTER TABLE [dbo].[ParcelRange] ADD  DEFAULT ((-1)) FOR [PickupAddressID]
GO

ALTER TABLE [dbo].[ParcelRange] ADD  DEFAULT ((-1)) FOR [OrganizationID]
GO

ALTER TABLE [dbo].[ParcelRange] ADD  DEFAULT ((-1)) FOR [DepotID]
GO

ALTER TABLE [dbo].[ParcelRange] ADD  DEFAULT ((0)) FOR [IsVTG]
GO

ALTER TABLE [dbo].[ParcelRange] ADD  DEFAULT ((0)) FOR [IsInternal]
GO

ALTER TABLE [dbo].[ParcelRange] ADD  DEFAULT ((0)) FOR [IsInterCompany]
GO

ALTER TABLE [dbo].[ParcelRange] ADD  DEFAULT (getdate()) FOR [Created]
GO

ALTER TABLE [dbo].[ParcelRange] ADD  DEFAULT (getdate()) FOR [Modified]
GO

ALTER TABLE [dbo].[ParcelRange] ADD  DEFAULT ((0)) FOR [UpdateCount]
GO

ALTER TABLE [dbo].[ParcelRange] ADD  DEFAULT (getdate()) FOR [ValidFrom]
GO

ALTER TABLE [dbo].[ParcelRange] ADD  DEFAULT (CONVERT([date],'9999-12-31')) FOR [ValidTo]
GO

ALTER TABLE [dbo].[ParcelRange] ADD  DEFAULT ((1)) FOR [IsActive]
GO

编辑(4)

我使用Entity Framework 5.0,会尝试更新到更高版本。

编辑(5) 更新到EF 6.1,同样的问题 这是我的连接字符串:

metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=XXX.XXX.XXX.XXX\DEV;initial catalog=DPDCDB_ODS;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient

2 个答案:

答案 0 :(得分:3)

"(I have included the field in my view as HiddenFor)"

由于它是数据库生成的主键,因此在create视图中它没有初始值,您不应使用HiddenFor来保存该属性。只需删除HiddenFor

即可

如果您使用脚手架向导创建EF控制器,您应该注意create视图中从不存在主键。

更新:http://robjoosentest.azurewebsites.net/parcelranges

我提供了提供的表脚本,创建了一个数据库,将其导出到Azure,创建了一个VS 2013 MVC Web应用程序,然后创建了基于EF模型的控制器和表的视图。然后我将它发布到Azure,它运行得很好(微软做得很好,让我们看看有人在5分钟内用Amazon S3做到这一点!):)。我怀疑它是你的一个库(可能是EF版本)的版本。否则,它可能是您的Web应用程序上其他数据库活动的副作用。

答案 1 :(得分:0)

当我向DBA提出这个问题时,他立刻指出了我正确的方向。

此特定表上有触发器.....这些触发器导致DBUpdateConcurrencyException。我们禁用了这些触发器,插入效果很好

我们现在必须找出如何模仿C#中的触发器或使用STP来更新/插入EF的记录。

感谢您的支持!

相关问题