Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework model update from database, custom properties is not recognising

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

like image 452
saulyasar Avatar asked Jul 30 '26 11:07

saulyasar


1 Answers

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;} 
}
like image 93
Philip Smith Avatar answered Aug 02 '26 01:08

Philip Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!