c# - 返回 Controller 中的 Linq 值并将其传递给 View

标签 c# asp.net-mvc entity-framework linq

返回所需值并将其传递给 View 时出现问题。我在 LINQPad4 中运行 LINQ 查询,它返回正确的结果。我觉得我在这里缺少一些简单的东西。我用过这篇文章HERE作为引用

我得到了

CS1061: 'IEnumerable' does not contain a definition for 'FirstName' and no extension method 'FirstName' accepting a first argument of type 'IEnumerable' could be found (are you missing a using directive or an assembly reference?)ERROR. \

当我运行并单步执行代码时,我没有看到任何值,并且给出的消息是

Message = "Unable to create a constant value of type 'System.Object'. Only primitive types or enumeration types are supported in this context."

更新

更改 @model IEnumerable<Login.Models.EditProfile> 的 View 至@model Login.Models.EditProfile帮助解决了我遇到的 CS1061 错误,至于 LINQ 查询不起作用,请查看下面 Titian 接受的答案。

任何帮助将不胜感激。 如果我可以提供更多信息,请告诉我。

/ Controller /

public ActionResult Edit(int? id)
    {


        using (TDBEntities db1 = new TDBEntities())
        {
            var user =  (from a in db1.ExternalUsers
                        join b in db1.ExternalUserEmails on a.ExternalUserID equals b.ExternalUserID
                        join c in db1.ExternalUserPhones on a.ExternalUserID equals c.ExternalUserID
                        where a.ExternalUserID.Equals(id)
                        select new EditProfile {ExternalUserID = a.ExternalUserID, FirstName = a.FirstName, LastName = a.LastName, EmailAddress = b.EmailAddress, PhoneNumber = c.PhoneNumber });

                if (user == null)
                {
                    return HttpNotFound();
                }

            return View(user);
        }
    }

/型号/

    public partial class EditProfile
    {
      public string FirstName { get; set; }
      public string LastName { get; set; }
      public string EmailAddress { get; set; }
      public string PhoneNumber { get; set; }
      public int ExternalUserID { get; set; }

    }

/查看/

@model IEnumerable<Login.Models.EditProfile>
@using Login.Helpers

@{
 ViewBag.Title = "Update Employee";
 }

 <h2></h2>

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

<div class="form-horizontal">
    <h4>Update Employee</h4>
    <hr />

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

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

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

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

    <div class="form-group">
        <label class="resetPw control-label col-md-2 ">Reset Password</label>            
        <div> @Html.CheckBox("ResetPassword", false, new { @style = "margin: 10px 15px 0;" }) <i>(check to reset)</i></div>
    </div>


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

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

最佳答案

您想要添加 FirstOrDefault您的查询。即使没有值(空结果),Select 也会返回一个值(类型为 IQueryable<User> )。实际上,您想要该结果中的第一个值,或者如果没有匹配结果,则为 null:

        var user =  (from a in db1.ExternalUsers
                    join b in db1.ExternalUserEmails on a.ExternalUserID equals b.ExternalUserID
                    join c in db1.ExternalUserPhones on a.ExternalUserID equals c.ExternalUserID
                    where a.ExternalUserID == id
                    select new EditProfile {ExternalUserID = a.ExternalUserID, FirstName = a.FirstName, LastName = a.LastName, EmailAddress = b.EmailAddress, PhoneNumber = c.PhoneNumber })
                    .FirstOrDefault();

关于c# - 返回 Controller 中的 Linq 值并将其传递给 View,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47437340/

相关文章:

c# - 如何使用流体断言.ShouldBeNull()

c# - 当文件上传超过 ASP.NET MVC 中允许的大小时显示自定义错误页面

entity-framework - 我们可以将现有实体用于 Entity Framework 而不是 EF 生成的实体吗

c# - 如何在使用 Facebook Developer Toolkit 授予 offline_access 后立即获取 Facebook 无限 session key

c# - 如何检测到达 ScrollViewer 项目的末尾 (Windows 8)?

.net - 为什么连接字符串需要保留在主 Web 应用程序和 ASP.NET MVC 中的数据访问项目中

c# - MVC5申请表导致提交时有多个post请求

c# - NLog.Extended 从 2.0 升级到 4.6 后抛出 "Could not load type NLog.Web.NLogHttpModule"

c# - Entity Framework ,按日/周/月在日期时间工作

entity-framework - 我应该如何使用 EF 4.1 注释 CreatedOn 和 ModifiedOn 列?