问题
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