从视图模型返回单个用户的详细信息

时间:2012-10-09 10:20:42

标签: asp.net-mvc entity-framework ef-code-first

我有一个视图模型,其中包含用户详细信息以及来自两个名为User和UserDetails的不同模型的扩展用户详细信息。

在我的UsersController中,我的Details方法有以下内容 -

public ViewResult Details(RegisterViewModel viewModel)
        {

            User currentuser = context.Users
                .Include("UserDetails")
                .Where(i => i.UserName == viewModel.UserName)
                .First();

            currentuser.UserDetails = new UserDetails();

            return View(currentuser);   
        }

在我的详细信息视图中,我从 -

开始
@model TRS.ViewModels.RegisterViewModel

然后尝试列出viewmodel中的detials,例如

<tr>
    <td>User Name</td>
    <td>@Model.UserName</td>

</tr>

但是当我转到用户的详细信息页面时,我收到此错误 -

Server Error in '/' Application.

Sequence contains no elements

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.InvalidOperationException: Sequence contains no elements

Source Error: 


Line 37:         {
Line 38:             
Line 39:             User currentuser = context.Users
Line 40:                 .Include("UserDetails")
Line 41:                 .Where(i => i.UserName == viewModel.UserName)

我显然做错了什么但却找不到什么。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

你做错了很多事。第一个是您的LINQ查询,您在其中搜索数据库UserName匹配viewModel.UserName的记录。但是,如果在最后尝试调用.First()方法时此查询未返回任何结果,则会出现异常。因此,您可以测试查询是否返回结果:

User currentuser = context.Users
    .Include("UserDetails")
    .Where(i => i.UserName == viewModel.UserName)
    .FirstOrDefault();
if (currentuser == null)
{
    // no records were found in the database that match this query
    return HttpNotFound();
}

您的代码出现的另一个问题是,您的视图被强类型化为TRS.ViewModels.RegisterViewModel,但您的Details控制器操作正在将User模型传递给此视图,但该视图无效。您需要将视图模型传递给它。

此外,还不是很清楚如何调用此Details操作以及视图模型作为参数传递的值是什么。您确定要将任何值传递给请求吗?否则所有属性都将为空,这可能解释为什么LINQ查询找不到任何记录。