Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
592 views
in Technique[技术] by (71.8m points)

entity framework - Update Model From Database (Database First)

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?

OR

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

http://jnye.co/Posts/19/adding-validation-to-models-created-by-entity-framework-database-first-c

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

Say you have a model like

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

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 {
}

You then define your validation in the UserMetadata class as follows

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

EDIT

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...