Best practice for editing MVC3 auto generated code?
Asked Answered
M

2

7

Im sorry if this is in the wrong place, however I think it is.

So I when creating an MVC3 internet application I used a database first method and my classes were generated for me. I am new to MVC3 and fairly new to c# and visual studio although I do have a little experience.

The auto-generated code warns that editing may cause unexpected results and the changes will be removed if the code is regenerated. As I understand it that means changes to the database, rerunning the tt files or updating the model.

However is it ok practice to edit it, and just keep a track of changes incase i need to regenerate, or is there a better way to go about it?

Thanks for any help.

Mcguinness answered 29/8, 2012 at 12:53 Comment(0)
C
11

The classes generated should be partial classes so you should be able to externally manage enhancements by making your own partial class with the same namespace and name.

Cupric answered 29/8, 2012 at 12:55 Comment(4)
+1 "partial" keyword is the right way, how to manage autogenerated and customized code together.Seamark
Thank you, will read up on partial classes and how to put them together. Will accept when it lets me. :)Mcguinness
So if I have a public 'partial class pagetest' in a class file called pages.cs and the auto generated class page is called news_page but also called 'partial class pagetest'will this work? they are both in model and both under the same namespace project.Models. However the auto-generated partial class is in the .edmx file. does the other half of the partial class need to be moved in there as well?Mcguinness
As long as the generated class and your custom class share the same namespace and name. In your example you would want to name your custom class news_page.Cupric
G
1

In the model first approach, using the default code generation strategy on you EDMX file, the classes generated for you DbContext and Entity classes are all partial classes.

So, depending on your type of changes, if you want to extend these generated classes, just create a new partial class with you custom code in it. Your partial's will not be overwritten by the code generator.

Grimm answered 29/8, 2012 at 13:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.