Flowra
Flowra

Reputation: 1408

How to save code in the model classes of mvc entity framework even the classes deleted?

Sometimes when I update in the database, and go update the model from database EntityFramework classes gets deleted after update, I searched a lot for a solution but I found that I have to delete edmx file and create it again.
I do that and the problem solved but the code I wrote in the model classes removed like the validation code, is there anyway can I keep the code I wrote even I delete and recreate edmx file ?

Upvotes: 1

Views: 135

Answers (1)

Matt
Matt

Reputation: 1264

EntityFramework will rebuild/generate all of the classes every time you change something.
If I got your problem right, I suggest using metadata classes:

public class EntityModel{
    public int Test {get; set;}
}

public class EntityModel2{
    public int Test2 {get; set;}
}

Then create 2 new files: Metadata.cs and PartialClasses.cs

Metadata.cs

public class Metadata{
    public class EntityModelMetadata { 
        [JsonIgnore] //or whatever you need
        public int Test {get; set;}
    }

    public class EntityModel2Metadata { 
        [XmlIgnore] //or whatever you need
        public int Test2 {get; set;}
    }
}

PartialClasses.cs

namespace YourNamespace{
    [MetadataType(typeof(EntityModelMetadata))]
    public partial class EntityModel {}

    [MetadataType(typeof(EntityModel2Metadata))]
    public partial class EntityModel2 {}
}

You need to create _Metadata class for each model you want to change and than you need to connect metadata class with EntityFramework class in PartialClasses.cs in the same way like shown.

Upvotes: 2

Related Questions