ASP MVC数据库优先 - 刷新EF实体框架时丢失所有验证

时间:2014-05-15 20:50:27

标签: c# asp.net-mvc entity-framework asp.net-mvc-4

我有这个恼人的问题,每次我想刷新我的实体框架架构(数据库优先),我丢失了我编写的所有验证代码(使用资源进行翻译等等)然后我需要回来我之前的代码来自版本控制,并以刷新模式之前的方式覆盖它。我确实找到了一个补丁来解决这个问题,但我发现它有一些开销......我需要一些关于如何处理这个问题的建议..请!因此,请说我的模型带有验证和资源(问题更短)如下:

public partial class tblReport
{
    public int id { get; set; }

    [Display(ResourceType = typeof(Resources.Admin), Name = "ReportName")]
    [Required(ErrorMessageResourceType = typeof(Resources.Admin), ErrorMessageResourceName = "Required")]
    public string reportName { get; set; }

    [Display(ResourceType = typeof(Resources.Admin), Name = "CreatedDate")]
    [Required(ErrorMessageResourceType = typeof(Resources.Admin), ErrorMessageResourceName = "Required")]
    public DateTime dtCreated { get; set; }
}

刷新EF Schema后,它将清除所有内容并将其恢复为默认值,如下所示:

public partial class tblReport
{
    public int id { get; set; }

    public string reportName { get; set; }

    public DateTime dtCreated { get; set; }
}

现在我找到了一个补丁,就像我说的那样,扩展tblReport类并将所有验证放在那里,但这相当于EF Schema的1比1副本并插入验证......所以我按照以下方式进行扩展:

public class tblReportModel : tblReport
{
    public int id { get; set; }

    [Display(ResourceType = typeof(Resources.Admin), Name = "ReportName")]
    [Required(ErrorMessageResourceType = typeof(Resources.Admin), ErrorMessageResourceName = "Required")]
    public string reportName { get; set; }

    [Display(ResourceType = typeof(Resources.Admin), Name = "CreatedDate")]
    [Required(ErrorMessageResourceType = typeof(Resources.Admin), ErrorMessageResourceName = "Required")]
    public DateTime dtCreated { get; set; }

    public tblReport ToTblReport()
    {
        tblReport tReport = new tblReport();

        tReport.dtCreated = this.dtCreated;
        tReport.reportName = this.reportName;
        tReport.id = this.id;

        return tReport;
    }

    public static tblReportModel ToTblReportModel(tblReport createdReport)
    {
        tblReportModel mReport = new tblReportModel();

        mReport.dtCreated = createdReport.dtCreated;
        mReport.reportName = createdReport.reportName;
        mReport.id = createdReport.id;

        return mReport;
    }
}

我发现这么多工作都没有,不仅如此,我需要更新我的控制器中的所有代码,并针对创建/编辑页面的新tblReportModel进行操作,以便他们获得验证完成。我确实以这种方式工作但是开销太大了......哦,这样做,我也得到一堆警告说

'IntranetApplication.Models.tblReportModel.dtCreated' hides inherited member 'IntranetApplication.Models.tblReport.dtCreated'. Use the new keyword if hiding was intended.

请!!!有谁有比这更好的解决方案???

1 个答案:

答案 0 :(得分:0)

使用MetadataType或扩展自动生成的类都是痛苦的方法 - 阅读Fals发布的问题,你会明白我的意思。

我所做的是将所有数据访问层代码放在一个单独的项目中。然后,我使用我的Business Objects创建另一个项目(我将验证添加到这些项目中)并使用AutoMapper在DAL和Business Objects之间映射对象。

这种方法可以更好地分离关注点,并且可以在您需要/想要时轻松切换到功能中的另一个ORM。这将是在AutoMapper中重新映射对象的问题。