繁体   English   中英

在使用实体框架的MVC4 Intranet应用程序中无法在Razor语法中使用HtmlHelper

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

我正在为简单的Intranet使用C#MVC4,Razor语法和实体框架。 我使用EF从称为PrinterMapping的现有数据库表中创建模型。 创建后看起来像这样:

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

我扩展了部分类,以便它具有不在数据库表中的属性,但是无论如何我都希望它存在。

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

在HomeController的Create操作中,我基于捕获从保存到数据库中返回的所有Exception消息来设置ExceptionMessage属性。 我想在Index.chtml视图上显示此属性。

我无法正确理解使用Link的强类型HTML助手。 所以我有:

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

尝试运行应用程序时出现以下错误:

编译器错误信息:

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?)

嗯? EF较早时为我创建了以下代码,并且以下代码没有问题:

<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>

唯一的区别是MTPrinter,NTPrinter和Active Properties是由EF创建的,而我自己创建了ExceptionMessage属性。

请问有什么好心的人可以解释一下发生了什么吗? 非常感谢。

发生的情况是,您扩展了PrinterMapping类定义并添加了一个新属性,该属性在EF模型中也未定义,并且数据库中不存在该列。

当您返回PrinterMapping的列表时,请尝试从数据库中获取所有数据,但是由于无法映射ExceptionMessage属性,因此该视图失败。

您可以使用Bind属性(请参见此处的 Doc)在对象绑定过程中排除或包括您的属性:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM