Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a new table to model (edmx) without updating the other models in Database First Entity Framework MVC application

I have an MVC 5 application that uses Entity Framework 6 Database First approach.

So far It is working well, but I have come across an unwanted behaviour.

If I select 'Update Model From Database', select the 'Add' Tab, and then select the Tables or Views I would like to add and click Finish, it adds the Tables and/or Views I specified no problem.

However, the unwanted behaviour is that, even though I didn't select the Refresh Tab, it seems every single model is automatically being refreshed.

This means all my custom Attributes on my models are being removed.

Is there any way to specify to only add the specified Tables or Views without refreshing all models, or if it refreshes all models, to retain the Attributes I have specified?

Visual Studio information: Microsoft Visual Studio Professional 2013 Version 12.0.40629.00 Update 5 Microsoft .NET Framework Version 4.5.51650

Installed Version: Professional

Is this a bug or intended use?

Thanks

Neill

like image 642
Neill Avatar asked Feb 05 '16 09:02

Neill


2 Answers

In order to modify autogenerated classes it's advised to use a partial class, that way your changes won't be lost when the class is refresh / generated again.

Simple example of a class and a partial class expanding on its attributes and methods

// Assume this is autogenerated by EntityFramework
public class Book {
    public int Id {get; set;}
    public string Title {get; set;}
}

// In a different file.cs
public partial class Book {
    [Required]
    public string Author {get; set;}

    public override ToString(){
        // Some code goes here
    }
}

In that example, if EntityFramework generates a new Book model, the changes you've done to that model via the partial class won't be lost at all.

Check out this article for more information on partial classes and this question for more info on the advantages of using partial classes.

Edit: if you need to add attributes to existing properties of your autogenerated class this answer might help you out as well.

like image 179
Alves RC Avatar answered Oct 03 '22 22:10

Alves RC


You really need to use partial classes so that you can refresh the edmx to your heart's content.

look here for a great tutorial on the subject.

like image 30
rory Avatar answered Oct 03 '22 21:10

rory