MVC 5 - 方法“...”的类型参数无法从使用中推断出。尝试显式指定类型参数。

6
我已经学习MVC 5几周了,一直没有遇到什么问题,直到昨天。昨晚我打开VS来处理我的项目时,一切都正常工作。但是现在出现了以下问题:
首先,我停止了当前的项目,创建了一个使用相同数据库模型的新项目。该数据库是Azure SQL数据库。对于我创建的每个对象,我都创建了自己的类来应用数据注释,就像这样:(由于有很多数据注释,我删除了它们,但错误仍然存在)。
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;

namespace Dyad.GreenvilleFoodTrucks.Data
{
[MetadataType(typeof(LocationMetadata))]
public partial class Location
{
}

public class LocationMetadata
{
    public int ID { get; set; }
    public int TruckID { get; set; }
    public Nullable<System.DateTime> StartTime { get; set; }
    public Nullable<System.DateTime> EndTime { get; set; }
    public Nullable<System.DateTime> Date { get; set; }
    public string Description { get; set; }
    public string Address { get; set; }
    public string State { get; set; }
    public string ZIP { get; set; }

    public virtual Truck Truck { get; set; }
}
}

并且,这是从我的数据库创建的对象EF:

namespace Dyad.GreenvilleFoodTrucks.Data
{
using System;
using System.Collections.Generic;

public partial class Location
{
    public int ID { get; set; }
    public int TruckID { get; set; }
    public Nullable<System.DateTime> StartTime { get; set; }
    public Nullable<System.DateTime> EndTime { get; set; }
    public Nullable<System.DateTime> Date { get; set; }
    public string Description { get; set; }
    public string Address { get; set; }
    public string State { get; set; }
    public string ZIP { get; set; }

    public virtual Truck Truck { get; set; }
}
}

我使用新创建的模型创建了一个支架项目,使用的上下文是 EF 创建的上下文而不是 ApplicationDBContext。

现在当我进入生成的视图时,ViewBag.Title = "title" 会给我这个错误:"需要编译动态表达式的一个或多个类型无法找到。您是否缺少引用?" 请注意,这在所有 CRUD cshtml 文件以及索引文件中都会发生。

此外,每个 @Html.LabelFor / @Html.DisplayNameFor 以及以 "For" 结尾的任何内容都会给我这个错误:"无法从使用中推断方法 'System.Web.Mvc.Html.DisplayNameExtensions.DisplayNameFor(System.Web.Mvc.HtmlHelper, System.Linq.Expressions.Expression>)' 的类型参数。请明确指定类型参数。"

以下是视图的示例。这是全部自动生成的,所以我没有更改任何内容。

@model Dyad.GreenvilleFoodTrucks.Data.Location

@{
ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm()) 
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Location</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.TruckID, "TruckID", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("TruckID", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.TruckID, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.StartTime, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.StartTime, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.StartTime, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.EndTime, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.EndTime, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.EndTime, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Date, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Date, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.State, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.State, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.State, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.ZIP, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.ZIP, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.ZIP, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}

<div>
@Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}

以及它的控制器:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Dyad.GreenvilleFoodTrucks.Data;

namespace Dyad.GreenvilleFoodTrucks.Controllers
{
public class LocationsController : Controller
{
    private GreenvilleFoodTrucksEntities db = new GreenvilleFoodTrucksEntities();

    // GET: Locations
    public ActionResult Index()
    {
        var locations = db.Locations.Include(l => l.Truck);
        return View(locations.ToList());
    }

    // GET: Locations/Details/5
    public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Location location = db.Locations.Find(id);
        if (location == null)
        {
            return HttpNotFound();
        }
        return View(location);
    }

    // GET: Locations/Create
    public ActionResult Create()
    {
        ViewBag.TruckID = new SelectList(db.Trucks, "ID", "Name");
        return View();
    }

    // POST: Locations/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ID,TruckID,StartTime,EndTime,Date,Description,Address,State,ZIP")] Location location)
    {
        if (ModelState.IsValid)
        {
            db.Locations.Add(location);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.TruckID = new SelectList(db.Trucks, "ID", "Name", location.TruckID);
        return View(location);
    }

    // GET: Locations/Edit/5
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Location location = db.Locations.Find(id);
        if (location == null)
        {
            return HttpNotFound();
        }
        ViewBag.TruckID = new SelectList(db.Trucks, "ID", "Name", location.TruckID);
        return View(location);
    }

    // POST: Locations/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "ID,TruckID,StartTime,EndTime,Date,Description,Address,State,ZIP")] Location location)
    {
        if (ModelState.IsValid)
        {
            db.Entry(location).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.TruckID = new SelectList(db.Trucks, "ID", "Name", location.TruckID);
        return View(location);
    }

    // GET: Locations/Delete/5
    public ActionResult Delete(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Location location = db.Locations.Find(id);
        if (location == null)
        {
            return HttpNotFound();
        }
        return View(location);
    }

    // POST: Locations/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        Location location = db.Locations.Find(id);
        db.Locations.Remove(location);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}
}

在处理完所有这些问题后,我想指出的是,当我以管理员身份运行VS时,这一切都没有发生,这一点我不太理解。此外,每个编译和运行都像往常一样。

对于我冗长的说明,我深表歉意,但我不想遗漏任何细节。如果我误用了任何术语,请谅解,因为我对MVC和C#还不够熟悉。

如果还有其他需要包含的内容,请告诉我。


你有没有可能针对错误的框架进行目标设置,就像Jim在这里的回答中所述?(https://dev59.com/7G445IYBdhLWcg3wO3xu) - Jonesopolis
从Web.conf文件中: <compilation debug="true" targetFramework="4.5" /> - Jonathan Carroll
2个回答

3

有时候,视图文件夹内的web.config文件引用了MVC或Razor依赖项的旧版本或缺失版本,这可能会导致问题出现。如果您无法手动修复它,或找出哪个引用有问题,最简单的方法是创建一个新的MVC项目并将View文件夹中的web.config文件与现有项目的配置文件进行比较。

虽然运行或调试通常不会出错,但它确实会使Intellisense感到困惑。


刚才看了一下,新的 Views 文件夹中的 Web.Config 文件和我当前的文件完全相同。 - Jonathan Carroll
你有检查过Views子文件夹中是否有任何文件吗?我曾经遇到过一个项目,其中一个子文件夹中有一个“流氓”配置文件,它偶尔会搞砸一些东西,这让我花了一段时间才弄清楚发生了什么。如果不是这个问题,那么请确保从nuget导入的任何内容都不依赖于旧版本的Razor视图引擎或Web Pages框架。您也可以尝试卸载并重新添加MVC5 nuget包。 - Benjamin Anderson
所以我尝试了你提出的所有建议,但仍然无法解决它。我注意到一个问题是,在我的Web.Config中引用了MVC的5.2.0.0版本,而我从NuGet添加的版本是5.2.2.0。因此,我在Web.Config中进行了更改,但这仍然没有解决我的问题。是否还有其他需要更改的内容可能引用了旧版本的MVC? - Jonathan Carroll
我想不到其他的了。如果你正在使用VS2013,请确保没有安装任何Roslyn beta,它会导致Razor视图出现许多奇怪的问题。 - Benjamin Anderson
我感谢你的帮助。我重新安装了Windows 8,似乎解决了所有问题。我仍然想知道可能是什么原因导致的。再次感谢你的帮助。 - Jonathan Carroll

1
我在更改视图文件夹的web.config中的基本类型时遇到了这个问题。
我正确地更改了这个部分。
  <system.web.webPages.razor>
    <pages pageBaseType="My.CustomType">
  </system.web.webPages.razor>

然后我错误地将<system.web>部分更改为包括我的自定义类型。我不得不将其改回完全限定的System.Web.Mvc.ViewPage,类似于:

<system.web>
    <pages
        validateRequest="false"
        pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
    </pages>
</system.web>

在清理和重建项目后,所有类型参数错误都消失了,并且我仍然使用我在<system.web.webPages.razor>中定义的自定义类型来定义razor视图。

这是我在几周的无果后解决问题的方法。最初我通过重新安装Windows来修复它,但几天后问题又出现了。忘记在这里更新答案了。谢谢! - Jonathan Carroll

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接