【发布时间】:2014-05-18 06:02:16
【问题描述】:
我正在使用实体框架制作一个测试博客应用程序,并遇到了这个错误:
“无法创建‘TestBlog.Models.Tag’类型的常量值。仅 在此上下文中支持原始类型或枚举类型。”
我正在使用带有视图模型的 asp.net MVC 在我的视图和控制器之间传递数据。
在我的 ActionResult 编辑帖子的控制器中,我有这样的声明:
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 = post.Tags.Contains(tag)
当我评论该语句时,它不再显示错误。
这是我的 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; }
}
非常感谢任何建议。
谢谢
【问题讨论】:
标签: c# asp.net asp.net-mvc entity-framework