Eri*_*cGS 6 data-annotations ef-database-first asp.net-mvc-4 entity-framework-5
我有一个很大的数据库现有数据库,我首先使用EF 5.0数据库,我遇到的问题是,如果我[stringlength(50)]在类上创建任何数据装饰然后上传数据库,当我"上传从数据库"所有数据注释都消失了.如何保留它们?
这很简单:你做不到!因为这些代码是自动生成的,并且会在每次更新或更改时覆盖.
但是,您可以通过扩展模型来实现所需.假设EF为您生成了以下实体类:
namespace YourSolution
{
using System;
using System.Collections.Generic;
public partial class News
{
public int ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int UserID { get; set; }
public virtual UserProfile User{ get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
并且你想做一些工作来保存你的数据注释和属性.因此,请按照下列步骤操作
首先,在下面添加两个类(在任何你想要的地方,但最好是在哪里Models),如下所示:
namespace YourSolution
{
[MetadataType(typeof(NewsAttribs))]
public partial class News
{
// leave it empty.
}
public class NewsAttribs
{
// Your attribs will come here.
}
}
Run Code Online (Sandbox Code Playgroud)
然后将您想要的属性和属性添加到第二个类 - NewsAttribs这里.:
public class NewsAttrib
{
[Display(Name = "News title")]
[Required(ErrorMessage = "Please enter the news title.")]
public string Title { get; set; }
// and other properties you want...
}
Run Code Online (Sandbox Code Playgroud)
笔记:
1)生成的实体类和您的类的名称空间必须相同 - 这里YourSolution.
2)您的第一个类必须是partial,其名称必须与EF生成的类相同.
通过这个,你的属性再也没有丢失过......
| 归档时间: |
|
| 查看次数: |
3440 次 |
| 最近记录: |