Yes, I have a project where I'm using my EF 6.x entities as if they were also my ViewModels - no AutoMap for me - I've studied and understand the risks.
My database has a lot of natural keys. In my Code First POCOs, I have properties that look like this:
Partial Public Class ProfilePriceGroup
<Key> <DatabaseGenerated(DatabaseGeneratedOption.None)>
Public Property ProfileId As Long
Public Property TargetRegion As String
Public Property Discount As Decimal = 0D
End Class
I'm experimenting with editing the scaffolding templates (my project features the 'CodeTemplates' directory via the SideWaffle VSIX), and I'm specifically trying to affect the razor generated by default for MvcView/Edit.vb.t4
Since the key is important information to reflect back to the model binder, the default scaffold renders a hidden input, but, in the case where it is DatabaseGeneratedOption.None - I wish it would render an additional visible label so users readly understand what 'ProfileId' they are editing.
In other words, the default scaffolding presumes surrogate keys which would be un-interesting in the view, but, my keys ARE interesting for my views.
I'm not interested in the <HiddenInput(DisplayValue:=True)> DataAnnotation that is part of the System.Web.Mvc namespace that acheives this. I do want to keep my EF project free of the MVC libraries for now.
I can see readily how the current MVC scaffolding iterates over types of PropertyMetadata from a passed-in ModelMetadata parameter that is a type of Microsoft.AspNet.Scaffolding.Core.Metadata.ModelMetadata
But, how do I cross over and get this DatabaseGenerated attribute, which I think derives from the System.Data.Metadata.Edm namespace?
Here you can see the resulting scaffolding snippet for my Edit.vb.t4 template:
@Using (Html.BeginForm())
@Html.AntiForgeryToken()
@<div class="form-horizontal">
<h4><#= ConvertCamelCaseStr(ViewDataTypeShortName) #></h4>
<hr />
@Html.ValidationSummary(true)
<#
For Each modelProperty As PropertyMetadata in ModelMetadata.Properties
If (modelProperty.Scaffold) AndAlso (Not modelProperty.IsAssociation) Then
If (modelProperty.IsPrimaryKey) Then
If (modelProperty.IsAutoGenerated) Then
#>
@Html.HiddenFor(Function(model) model.<#= modelProperty.PropertyName #>)
<#
Else
#>
<!-- natural key - we will show the value and a hidden input -->
<div class="form-group">
@Html.LabelFor(Function(model) model.<#= modelProperty.PropertyName #>, New With { .class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DisplayFor(Function(model) model.<#= modelProperty.PropertyName #>)
@Html.HiddenFor(Function(model) model.<#= modelProperty.PropertyName #>)
</div>
</div>
<#
End If
ElseIf (Not modelProperty.IsReadOnly)
#>
The part that makes my scaffold work is the If (modelProperty.IsAutoGenerated) Then
piece.. my special stuff is in the Else
and is a departure from the OOTB T4 MVC 5/EntityFramework templates