各位程序员,大家好!
对于 MVC C#,我有点新手,但这是我的问题。我有三个关系型 MySQL 表;用户、头衔和用户头衔。
用户看起来像这样:
+---------------+----------+
| currentUserId | UserName |
+---------------+----------+
| 1 | Dave |
+---------------+----------+
标题如下所示:
+---------+-------+
| TitleId | Title |
+---------+-------+
| 1 | BS |
| 2 | MD |
| 3 | PHD |
| 4 | BA |
+---------+-------+
...UserTitles 看起来像这样:
+--------+---------+
| UserId | TitleId |
+--------+---------+
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 1 | 4 |
+--------+---------+
现在,在我看来,我想根据数据库中分配给 Dave 的专业名称显示“Dave,BS,MD,PHD,BA”。
现在我可以轻松地在 MySQL 查询中执行此操作,并且它会起作用:
select Title from titles
INNER JOIN UserTitles on UserTitles.TitleId = titles.TitleId
where UserTitles.UserId = currentUserId;
现在我必须将其转换为 Linq.Lambda。这是我做的,没有显示任何错误。
在 Controller 中:
ViewData.Add("FirstName", Users.Name);
var thisresult =
_contentService.Titles.Join(_contentService.UserTitles,
x => x.Id, y => y.TitleId, (x, y) => new {x, y})
.Where(@t => @t.y.UserId == currentUserId)
.Select(@t => new SelectListItem {Value = @t.x.TitleString}).ToList();
更新 (感谢大家的支持)
IEnumerable<String> thisresult = _contentService.Titles
.Join(_contentService.UserTitles.Where(x => x.UserId == currentUserId),
t => t.Id,
ut => ut.TitleId,
(t, ut) => t.TitleString);
var model = new ManageUserViewModel()
{
Titlelist = thisresult.ToList()
};
return View(model);
其中 _contentService 调用我的数据库。
在 View 模型中:
public IEnumerable<SelectListItem> Titlelist { get; set; }
更新
public IEnumerable<String> Titlelist { get; set; }
查看中:
@ViewBag.FirstName,
@foreach (var x in Model.Titlelist)
{@x.Value}
更新
@foreach (var title in Model.Titlelist)
{
@Html.Raw(title)
}
输出:
“/”应用程序中的服务器错误。 不支持指定的方法。
有什么想法吗?
最佳答案
var thisresult =
_contentService.Titles.Join(_contentService.UserTitles,
x => x.Id, y => y.TitleId, (x, y) => new {x, y})
.Where(@t => @t.y.UserId == currentUserId)
.Select(@t => new {Title = @t.x.TitleString}).ToList();
将 ToString() 更改为 ToList();
编辑:
var thisresult =
_contentService.Titles.Join(_contentService.UserTitles,
x => x.Id, y => y.TitleId, (x, y) => new {x, y})
.Where(@t => @t.y.UserId == currentUserId)
.Select(@t => new SelectListItem{
Selected = //write your stuff here ,
Text = //write your stuff here //,
Value = //write your stuff here }).ToList();
编辑2
var thisresult = _contentService.Titles.Join(_contentService.UserTitles,
x => x.TitleId, y => y.TitleId, (x, y) => new {x, y})
.Where(@t => @t.y.UserId == currentUserId)
.Select(@t => new SelectListItem{
Selected = //write your stuff here ,
Text = //write your stuff here //,
Value = //write your stuff here }).ToList();
关于c# - 如何在 foreach 循环中使用 linq lambda C# MVC razor 枚举从关系数据库中选择的专业职称的用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32653821/