在这个上下文实体框架中只支持基元类型或枚举类型
本文关键字:类型 支持 枚举 上下文 实体 框架 | 更新日期: 2023-09-27 18:03:47
我正在使用enity框架制作一个测试博客应用程序,遇到了以下错误:
"无法创建类型为"TestBlog.Models.Tag"的常量值。仅在此上下文中支持基元类型或枚举类型。">
我使用asp.net MVC和视图模型在视图和控制器之间传递数据。
在我的ActionResultEdit帖子的控制器中,我有这样的声明:
return View("Form", new PostsForm
{
Tags = TestBlog.Tags.Select(tag => new TagCheckBox
{
Id = tag.Id,
Name = tag.Name,
IsChecked = post.Tags.Contains(tag)
}).ToList()
});
我也尝试过这个版本:
return View("Form", new PostsForm
{
Tags = (from item in TestBlog.Tags
select item).Select(tag => new TagCheckBox
{
Id = tag.Id,
Name = tag.Name,
IsChecked = post.Tags.Contains(tag)
}).ToList()
});
问题似乎是由以下原因引起的:
IsChecked=发布。标签。包含(标签(
当我评论该语句时,它不再显示错误。
这是我的Tag.cs型号
public class Tag
{
public Tag()
{
this.Posts = new HashSet<Post>();
}
public int Id { get; set; }
public string Slug { get; set; }
public string Name { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
这是我的视图模型:
public class TagCheckBox
{
public int? Id { get; set;}
public string Name { get; set; }
public bool IsChecked { get; set;}
}
public class PostsForm
{
public bool IsNew { get; set; }
public int? PostId { get; set; }
[Required, MaxLength(128)]
public string Title { get; set; }
[Required, MaxLength(128)]
public string Slug { get; set; }
[Required, DataType(DataType.MultilineText)]
public string Content { get; set; }
public IList<TagCheckBox> Tags { get; set; }
}
如有任何建议,不胜感激。
感谢
EF不知道您的类TagCheckBox,并且无法在SQL中创建它的实例。这样试试吧。
(无法通过我的手机设置格式,抱歉(。
return View("Form", new PostsForm
{
Tags = (from item in TestBlog.Tags
select item).Select(tag => new
{
Id = tag.Id,
Name = tag.Name,
IsChecked = post.Tags.Any(t => t.Id == tag.Id)
}).
.AsEnumerable()
.Select(tag => new TagCheckBox
{
Id = tag.Id,
Name = tag.Name,
IsChecked = tag.IsChecked
})
.ToList()
});
IsChecked = post.Tags.Select(x => x.Id).Contains(tag.Id)
更新
但实际上,通过设置导航属性属性,您应该能够调用:
Tags = post.Tags.Select(x => new TagCheckBox { Id = x.Id, Name = x.Name, IsChecked = x.IsChecked }).ToList();