是否可以为实体设置默认对象?为实体框架导航属性设置默认对象
说我有一个Person
实体,最初没有要求Profile
。
现在我需要一个Profile
- 但有一些现有的实体目前没有Profile
。
有没有一种方法,我可以提供,当他们在未来会加载这些实体默认的对象,因此,使用Person
实体任何人都可以假定Profile
永远不能为null,总是有一个值 - 即使它是一个默认值。
下面你可以看到我已经尝试过 - 哪些会创建一个默认值 - 但即使数据库中有某些东西,它总是会返回默认对象。
- 如果
Profile
是null
我想回到默认initialzied对象 - 如果
Profile
不null
我想从数据库中
此外返回对象 - 这将是将“default”对象附加到我的dbcontext最明智的方法是什么?
我怎样才能达到这个理想的行为?
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
}
我知道你可以初始化集合,使它们不为null,但我也想初始化一个对象。
当你在数据库中加载没有配置文件的'Person'对象时,你想要发生什么,然后更新它的一些属性并保存回去? EF应该为数据库中的这个人创建一个配置文件吗? –
@YacoubMassad我希望没有'Profile'的'Person'拥有'Profile'的实例化实例 - 除非调用SaveChanges()',否则不必保存 - 但我并不担心这个问题部分 - 我只是想实例化一个'Profile',如果它是空的,如果它不为空,就像正常情况下从数据库加载。 – Alex
这是什么'User'类?它是'Person'的基类吗? –