我正在使用 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>
我的 Controller 和 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”类型的常量值。在此上下文中仅支持原始类型或枚举类型。
请您参考如下方法:
这里你比较的是苹果(整数)和橙子( bool 值):
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()
{
...
}
