Custom properties in EF database first

岁酱吖の 提交于 2019-12-10 10:15:36

问题


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!


回答1:


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";
         }
    }
}



回答2:


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




回答3:


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;
        }
    }
}


来源:https://stackoverflow.com/questions/19021503/custom-properties-in-ef-database-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!