3

Good day!

I have created an EF model from database using database first aproach, and added myself several read only properties to entity class generated by EF which are not in database. Every time I update my model adding data from new tables I loose properties created, so I have to recreate them.

As an example in database I have property isFemale but in my class I've created

public string Gender
{
    get
    {
           if(isFemale) return "female";
           else return "male";
     }
}

My question is there a way to update the model from database, leaving properties generated by me?

Thank you!

Dovlet Mamenov
  • 581
  • 1
  • 7
  • 20
  • possible duplicate of [Extending Entity Framework Model to include new property](http://stackoverflow.com/questions/6099456/extending-entity-framework-model-to-include-new-property) – Mr.LamYahoo Sep 26 '13 at 07:11

3 Answers3

5

Add the properties on another Partial Class instead of the generated class. For example, if your generated class is of type Person, define another Partial class in the same project with the same namespace:

public partial class Person
{
    public string Gender
    {
        get
        {
            if(isFemale) return "female";
            else return "male";
         }
    }
}
Richard
  • 29,854
  • 11
  • 77
  • 120
  • Hi, Richard Thank you for your answer! I want to go farther and overwrite the property created by EF. Is that possible? As an example I have string BankAccount field in database and as the result generated in my entity class which accepts null values. I want to overwrite it, to return empty string if the value is null. public string BankAccount { get{if (_BankAccount==null) return ""; else return _BankAccount}}. Kind regards! – Dovlet Mamenov Sep 26 '13 at 17:35
  • 1
    You can't override properties in this way. You'll need to either use a separate property like you already are, or a function or extension method. – Richard Sep 26 '13 at 18:55
4

Using partial class will solve your problem but:

  • All parts of partial class must be defined in the same assembly
  • Properties from your partial part are not persisted to the database
  • Properties from your partial part cannot be used in linq-to-entities queries

read more

Community
  • 1
  • 1
Mr.LamYahoo
  • 1,536
  • 13
  • 28
  • The 'read more' link leads to the current thread. The correct link would be https://stackoverflow.com/a/6099964/1115382 – A Petrov Nov 14 '20 at 11:58
2

You could make your class partial and seperate it in two files, this is the way I use it with DatabaseFirst.

public partial class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public partial class Person
{
    public string FullName {
        get
        {
            return FirstName + " " + LastName;
        }
    }
}
Staeff
  • 4,994
  • 6
  • 34
  • 58