我在带有MVC的表中列出了来自SQL Server数据库的一些数据。我需要的是仅能够显示UserID等于实际经过身份验证的用户的数据。

这是我目前所做的:

 public class ManageViewModel
  {
    public string FileName { get; set; }

    public string ContentType { get; set; }

    public string Format { get; set; }
  }


我的看法:



@model IEnumerable<Transcode.Models.ManageViewModel>
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
<table style="width:100%">
    <tr>
        <th>File Name</th>
        <th>Actual Format</th>
        <th>Requested Format</th>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>@item.FileName</td>
            <td>@item.ContentType</td>
            <td>@item.Format</td>
        </tr>
    }
</table>





我的控制器和LINQ查询:

public class ManageController : Controller
{
    ApplicationDbContext db = new ApplicationDbContext();
    public ActionResult Index()
    {
        var Model = from file in db.Conversions
                    join codec in db.Codecs on file.CodecID equals codec.CodecID
                    where file.UserID.Equals(User.Identity.IsAuthenticated)
                    select new ManageViewModel
                    {
                        FileName = file.FileName,
                        ContentType = file.ContentType,
                        Format = codec.Format
                    };
        return View(Model);

    }
}


我的@foreach(模型中的var项)出现以下错误:

EntityFramework.SqlServer.dll中发生类型为'System.NotSupportedException'的异常,但未在用户代码中处理
附加信息:
无法创建类型为'System.Object'的常量值。在此上下文中仅支持原始类型或枚举类型。

最佳答案

在这里,您正在比较苹果(整数)和橙子(布尔值):

where file.UserID.Equals(User.Identity.IsAuthenticated)


您不应该将苹果(整数)与苹果(整数)进行比较吗?因此,您可以使用GetUserId()扩展方法从获取当前已认证用户的ID开始:

string userId = this.User.Identity.GetUserId();


然后将其转换为整数或标识符的任何基础类型:

int id = int.Parse(userId);


然后可以在LINQ子句中进行比较:

where file.UserID == id


最后但并非最不重要的一点,由于您正在与用户打交道,因此您的Index动作应使用[Authorize]属性修饰,以确保只有经过身份验证的用户才能调用它:

[Authorize]
public ActionResult Index()
{
   ...
}

关于c# - MVC LINQ,其中UserID等于已认证的用户,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37100313/

10-12 12:43
查看更多