I am using code first with EF6 and AspNetCore to create hundreds of tables and views using the scaffold templates.
In simple navigation models
public class BaseModel
{
public int Id { get; set; }
[MaxLength(100)]
[Column(TypeName = "varchar(100)")]
public string? BaseModelNo { get; set; }
public virtual ICollection<SubModel>? SubModels { get; set; }
}
public class SubModel
{
public int Id { get; set; }
[MaxLength(100)]
[Column(TypeName = "varchar(100)")]
public string? SubModelNo { get; set; }
public int BaseModelId { get; set; }
public virtual BaseModel? BaseModelNo { get; set; }
}
When scaffolding, the controller:
...
ViewData["BaseModelId"] = new SelectList(_context.BaseModels, "Id", "Id", model.BaseModelId);
return View();
...
and in Details Views
...
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.BaseModel.Id)
</dd>
...
My Question is
Is there a way to let it instead bind automatically to the first property that is not the primary key, Id
, which in this example should be BaseModelNo
So in the controller:
...
ViewData["BaseModelId"] = new SelectList(_context.BaseModels, "Id", "BaseModelNo", model.BaseModelId);
return View();
...
and in Details Views
...
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.BaseModel.BaseModelNo)
</dd>
...
What I tried: Changing the order of the model
For anyone who had this issue or find it interesting, I posted the source on gihub at here
I would still like someone to explain why it works this way, but for now, it works, by simply having the model in a seperate project.
In my example, the entities in Models.cs scaffold binds to Id, where as the entities in OtherModels.cs scaffolds binds to the first non nullable string property.
public class OtherBase
{
public int Id { get; set; }
public string? Name1 { get; set; }
public string Name2 { get; set; }
public virtual ICollection<OtherSub> OtherSub { get; set; }
}
So in this case will bind to Name2.