2
votes

I just want to ask general question for Entity Framework. When i want to update my model from database or add new item to model from database, I'm losing all my custom properties

In Example

My Sql Table
Test
Id     int
TestId int

EF creates model automatically
public class Test
{
     public int    Id {get;set;}
     public int    TestId {get;set;}
}
//I want to add custom property on class 
public class Test
{
     public int    Id {get;set;}
     public int    TestId {get;set;}
     public string TestName {get;set;} //I added custom property
}

but when i update model, i'm losing custom properties and everytime i need to add it again and again

Do you have any solution for this?

Thanks

1
Have you done a migration in order to update your DB schema?Atlasmaybe
No i don't use that @Atlasmaybesaulyasar
What are you using then?Atlasmaybe
Did you read my question? As i told there when i want to add new table or update any sp or add new sp i'm using update model from database function so i'm losing all custom properties @Atlasmaybesaulyasar
Being patronizing won't help you here... Anyway, your question isn't very clear, that's why I asked what are you using... But maybe you should start here : docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/… or here if you don't use aspnet core docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/…Atlasmaybe

1 Answers

1
votes

You need to use the partial keyword. Partial Classes and Methods (C# Programming Guide)

EF should add the partial keyword to the classes it creates (if it doesn't then you need to work out how to get the process you use to add the keyword - usually by editing a .tt file). You then can create a separate .cs file with the same class definition. In your case:

public partial class Test

The C# compiler will then treat the two definitions as the same definition and "add" them together. This works if you follow a few simple rules.

  • Both definitions must be the same and include the partial keyword.
  • Both must be defined in the same module (.exe, .dll)
  • Both must be defined in the same namespace.

In this way you have one class definition that EF maintains and one that you maintain. EF will not overwrite your custom properties.

Your class will simply be:

public partial class Test
{
    public string TestName {get; set;} 
}