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
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.
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;}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With