I created a database first entity framework MVC5 application. The table has a string primary key.I used scaffolding to create the controller. My controller/Index works fine but Details, Edit and Create doesn't work. If i use int primary key all CRUD works fine. Does EF not support the string primary keys.
Here is my Index.cshtml
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Owner)
</td>
<td>
@Html.DisplayFor(modelItem => item.Address)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Property_Ref }) |
@Html.ActionLink("Details", "Details", new { id=item.Property_Ref }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Property_Ref })
</td>
</tr>
}
This is my Controller
// GET: /Property/
public ActionResult Index()
{
return View(db.Tables.ToList());
}
// GET: /Property/Details/5
public ActionResult Details(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Table table = db.Tables.Find(id);
if (table == null)
{
return HttpNotFound();
}
return View(table);
}
// GET: /Property/Create
public ActionResult Create()
{
return View();
}
All this code is generated by MVC5 Database first and using scaffolding for controller.
The Index works fine and list all records, When I click Details, I get an error Server Error in '/' Application.
http://localhost:51356/Property/Details/2 - here 2 is a string primary key![enter image description here][1]
Many thanks
As Jhoon Bey said, make sure that the table has 'Property_Ref' marked as Primary key before you build the EF data model from your database. FYR, the working code:
Table:

EF Model:

Controller:
private TestDbEntities1 db = new TestDbEntities1();
// GET: /Person/
public ActionResult Index()
{
return View(db.People.ToList());
}
// GET: /Person/Details/5
public ActionResult Details(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Person person = db.People.Find(id);
if (person == null)
{
return HttpNotFound();
}
return View(person);
}
// GET: /Person/Create
public ActionResult Create()
{
return View();
}
Index:
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Property_ref }) |
@Html.ActionLink("Details", "Details", new { id=item.Property_ref }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Property_ref })
</td>
</tr>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With