我正在尝试从多对多数据库表中获取我的帖子编辑页面的复选框值。但我收到错误,
CS0029:无法将类型“System.Collections.Generic.List
”隐式转换为“System.Collections.Generic.List”
Model
:
public class PostModel
{
[Key]
public int Id { get; set; }
public string? Title { get; set; }
public string? Description { get; set; }
public List<TagModel> Tags { get; set; }
// Many To Many
public List<PostTagModel> PostTags { get; set; }
}
ViewModel
:
public class EditPostViewModel
{
public string? Title { get; set; }
public string? Description { get; set; }
public List<int>? TagId { get; set; }
public List<TagModel>? TagList { get; set; }
}
Controller
:
[HttpGet]
public async Task<IActionResult> Edit(int id)
{
// Id Check
var post = await _postInterface.GetByIdAsync(id);
// Check
if (post == null)
{
return View("Error");
}
var postVM = new EditPostViewModel
{
Title = post.Title,
Description = post.Description,
TagId = post.Tags, // Where I receive error
// List
TagList = await _context.Tags.ToListAsync()
};
return View(postVM);
}
我尝试过的
我尝试使用许多不同的变量来实现
TagId
,但没有成功。这是一个示例:
var selectedTags = await _context.Posts.Select(p => p.Tags).SingleAsync();
var postVM = new EditPostViewModel
{
TagId = selectedTags, // Gives same or nearly similar errors
};
Tags
类的 PostModel
属性的类型为 List<TagModel>
,并且您尝试将其分配给 TagIds
类型,其类型为 List<int>?
。
要解决此问题,您必须获取
Tag
的所有 Id 并将其分配给 TagIds
。
var postVM = new EditPostViewModel
{
Title = post.Title,
Description = post.Description,
TagId = post.Tags.Select(x => x.Id).ToList(),
//^^^^^^^^^^^^^^^^^^^^^^^^^ This will project a new list of ids.
TagList = await _context.Tags.ToListAsync()
};