user3041439
user3041439

Reputation: 153

Unable to Use an HtmlHelper in Razor syntax in MVC4 Intranet App using Entity Framework

I am using C# MVC4, Razor syntax and Entity Framework for a simple intranet. I used EF to create my model from an existing database table called PrinterMapping. After creating it looks like this:

public partial class PrinterMapping
{
    public string MTPrinterID { get; set; }
    public string NTPrinterID { get; set; }
    public string Active { get; set; }
}

I extended the partial class so that it has a Property that is not in the database table but I want it there anyway.

public partial class PrinterMapping
{
    public string ExceptionMessage { get; set; }
}

In my HomeController's Create action, I set the ExceptionMessage Property based on catching any Exception messages returned from saving to the database. I want to display this Property on my Index.chtml view.

I am having trouble properly understanding strongly typed Html helpers that use Link. So I have:

@Html.DisplayTextFor(model => model.ExceptionMessage)

I get the following error while trying to run the app:

Compiler Error Message:

CS1061:
'System.Collections.Generic.IEnumerable<AccessPrinterMapping.PrinterMapping>'
does not contain a definition for 'ExceptionMessage' and no extension method 
'ExceptionMessage' accepting a first argument of type 
'System.Collections.Generic.IEnumerable<AccessPrinterMapping.PrinterMapping>'
could be found (are you missing a using directive or an assembly reference?)

Eh? EF earlier on created the following code for me and there are no problems with the following code:

<th align="left">
    @Html.DisplayNameFor(model => model.MTPrinterID)
</th>
<th align="left">
    @Html.DisplayNameFor(model => model.NTPrinterID)
</th>
<th align="left">
    @Html.DisplayNameFor(model => model.Active)
</th>

The only difference here is that MTPrinter, NTPrinter and Active Properties were created by EF and I created the ExceptionMessage Property myself.

Will some kind soul please explain a little bit of what is going on? Many thanks.

Upvotes: 1

Views: 363

Answers (1)

DJ.
DJ.

Reputation: 528

What is happening is that you have extended the PrinterMapping class definition and add a new property which is not defined either in the EF Model and not column exist in the database.

When you return the list of PrinterMapping the view try to fetch all the data from the database, but it fails beacuse it's unable to map the ExceptionMessage property.

You can use the Bind attribute (see Doc here), to either exclude or include your property in the object binding process:

public partial class PrinterMapping
{
    [Bind(Exclude="ExceptionMessage")]
    public string ExceptionMessage { get; set; }
}

Upvotes: 1

Related Questions