Is it possible to set a default object for an Entity?
Say I have a Person
entity that originally did not have a requirement for a Profile
.
Now I require a Profile
- but there are existing entities that do not currently have a Profile
.
Is there a way I can provide a default object for these Entities when they're loaded in future, so anyone using the Person
Entity can assume that Profile
is never null and always has a value - even if it's a default.
Below you can see what I've tried - which does create a default value - but even when there is something in the database it always return the default object.
- If the
Profile
isnull
I want to return a default initialzied object - If the
Profile
is notnull
I want to return the object from the database
Additionally - what would be the most sensible way to attach the "default" object to my dbcontext?
How can I achieve this desired behavior?
public class Person
{
[Key]
public int Id {get; set;}
private Profile _profile;
public virtual Profile Profile
{
get
{
return _profile ?? (_profile= new Profile
{
Person = this,
PersonId = Id
});
}
set
{
_profile = value;
}
// properties
}
}
public class Profile
{
[Key, ForeignKey("Person")]
public int PersonId {get; set;}
[ForeignKey("PersonId")]
public virtual Person Person{ get; set; }
// properties
}
I know you can initialize collections so that they're not null, but I'd like to initialize a single object too.