更新模型从数据库(数据库优先) [英] Update Model From Database (Database First)

查看:307
本文介绍了更新模型从数据库(数据库优先)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

,我一直在使用SQL Server中创建我的数据库,我将其导入到MVC3 Web应用程序。

I'm using MVC3 VS2010 with EF4.1, I have created my DB using SQL Server and I import it to the MVC3 Web Application.

我有一个挑战,在这里,我来的时候要更新数据库模型我失去了所有我的模型文件的修改,例如,如果我使用的属性在某些型号审定左右全部被覆盖的新模特属性

I have a challenge here, when I come to Update Model from Database I do lost all my models files modifications, for example if I'm using attributes in some models for validation or so all that is overwritten with the new model properties.

反正有更新型号从数据库中不失模型的信息?

Is there anyway to Update Model from Database without losing models' information?

在这里我要对我的模型定义的验证,而不是直接使用模型的文件?

where should I define validation on my models instead of using the models' files directly?

推荐答案

更新:由于这还是比较受欢迎的,我创建这个博客帖子

Update: As this is still relatively popular, I have created a blog post on this.

<一个href=\"http://jnye.co/Posts/19/adding-validation-to-models-created-by-entity-framework-database-first-c\" rel=\"nofollow\">http://jnye.co/Posts/19/adding-validation-to-models-created-by-entity-framework-database-first-c

如果您想验证的模型,而不是使用的ViewModels,使用部分类来定义属性验证。例如:

If you want to validate your models, and not use viewModels, use partial classes to define validation attributes. For example:

假设你有一个像

public class User {
    public string Name { get; set; }
}

如果你想要把一个字符串长度的验证就可以了,你需要创建一个分部类和利用 MetadataTypeAttribute (此住在System.ComponentModel.DataAnnotations)

If you wanted to put a string length validator on it you would need to create a partial class and utilise the MetadataTypeAttribute (this lives in System.ComponentModel.DataAnnotations)

下面的类应该在自己单独的文件中定义的不可以放在同一个文件作为自动生成的模型。

The following classes should be defined in their own separate file, NOT put in the same file as your auto generated models.

[MetadataTypeAttribute(typeof(UserMetadata))]
public partial class User {
}

您然后定义在 UserMetadata 类的验证如下:

You then define your validation in the UserMetadata class as follows

public class UserMetadata{
    [StringLength(50)]
    public string Name {get; set;}
}

修改

我刚刚发现这个文章,其中介绍了在一个小更详细的解决方案
http://themonitoringguy.com/tips-tricks/validating-microsoft-entity-framework-objects-c-mvc/

I just found this article which explains the solution in a little more detail http://themonitoringguy.com/tips-tricks/validating-microsoft-entity-framework-objects-c-mvc/

这篇关于更新模型从数据库(数据库优先)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆