Inserting in non identity ID column:
Table:
CREATE TABLE [dbo].[TestTable]( [Id] [int] NOT NULL, [Name] [nvarchar](50) NULL, CONSTRAINT [PK_TestTable] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]
Model:
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
namespace NoIdent.Models
{
[Table("TestTable")]
public class TestTable
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public string Name { get; set; }
}
public class testNoIdentEntities : DbContext
{
public DbSet TestTable { get; set; }
}
}
Without [Table("TestTable")], EF will create TestTableS - EF always add S (plural)
[DatabaseGenerated(DatabaseGeneratedOption.None)] is mandatory, to tell EF that ID is not identity
Create controller with scaffolding. Modify Create and Index view:
Create:
<fieldset> <legend>TestTable</legend> <div class="editor-label"> @Html.LabelFor(model => model.Id) </div> <div class="editor-field"> @Html.EditorFor(model => model.Id) @Html.ValidationMessageFor(model => model.Id) </div> <div class="editor-label"> @Html.LabelFor(model => model.Name) </div> <div class="editor-field"> @Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </div> <p> <input type="submit" value="Create" /> </p> </fieldset>
Index:
<table>
<tr>
<th>
Id
</th>
<th>
Name
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Id)
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
and that's all folks!