使用存储在数据库中的模型中的枚举值
我似乎不知道如何在 ASP.NET MVC 3 模型中使用枚举值(使用代码优先方法),以便将它们存储在数据库中并保留。
我的模型代码如下所示:
public class TestNews
{
public int Id { get; set; }
[Required]
public DateTime Date { get; set; }
[Required]
//[EnumDataType(typeof(TestNewsType))]?
public TestNewsType Type { get; set; }
[Required]
public string Title { get; set; }
}
public enum TestNewsType : short
{
Draft = 0,
PublishedPublicly = 1,
PublishedInternally = 2,
Removed = 3
}
重新创建数据库后,它包含表 TestNews,但它只包含列:
- Id
- Date
- Title
如何使其还将类型存储在数据库中?还应该使用 EnumDataType 注释吗?
我稍后想在控制器操作中使用它,例如:
public ActionResult Latest(int count=5)
{
var model = db.TestNews
.Where(n => n.Type == TestNewsType.PublishedPublicly)
.OrderByDescending(n => n.Date)
.Take(count)
.ToList();
return PartialView(model);
}
I don't seem to figure it out how to use enum values in an ASP.NET MVC 3 model (using code first approach) so that they are stored in a database and are preserved.
My model code looks like:
public class TestNews
{
public int Id { get; set; }
[Required]
public DateTime Date { get; set; }
[Required]
//[EnumDataType(typeof(TestNewsType))]?
public TestNewsType Type { get; set; }
[Required]
public string Title { get; set; }
}
public enum TestNewsType : short
{
Draft = 0,
PublishedPublicly = 1,
PublishedInternally = 2,
Removed = 3
}
After the database gets recreated it contains the table TestNews, but it contains only the columns:
- Id
- Date
- Title
How to make it also store the Type in the database? And also should the EnumDataType annotation be used?
I would later like to use it in a controller action like:
public ActionResult Latest(int count=5)
{
var model = db.TestNews
.Where(n => n.Type == TestNewsType.PublishedPublicly)
.OrderByDescending(n => n.Date)
.Take(count)
.ToList();
return PartialView(model);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实体框架 6 月 CTP< /a> 引入了 Enum 支持。
作为使用 CTP 的替代方法,MSDN 博客上有一篇关于 如何使用实体框架伪造枚举。
The June CTP of Entity Framework introduced Enum support.
As an alternative to using the CTP, at the MSDN blogs is an article on how to fake enums with Entity Framework.