将null对象设置为值

时间:2014-12-18 04:24:21

标签: c# database asp.net-mvc-4 oop model-view-controller

我需要能够在用户访问并且没有城市价值后编辑数据库中的用户。 每件事都有效,可以编辑,但我无法编辑城市。

thisuser.FirstName = user.FirstName;
thisuser.LastName = user.LastName;
thisuser.UserName = user.UserName;
thisuser.Password = user.Password;
if (thisuser.Address != null)
{
   thisuser.Address.City = user.Address.City;
}
else if (thisuser.Address == null) !I need help here
{

}

1 个答案:

答案 0 :(得分:4)

如果这是使用某种ORM数据层,您只需创建对象,设置其值,然后将其添加到父对象。

thisuser.FirstName = user.FirstName;
thisuser.LastName = user.LastName;
thisuser.UserName = user.UserName;
thisuser.Password = user.Password;

if (thisuser.Address == null)
{
    thisuser.Address = new Address();   // Make sure this is the type 
                                        // that Address should be
                                        // This also assumes that Address is 1 to 1
}

thisuser.Address.City = user.Address.City;

如果地址属性是可以包含多个地址的导航属性,那么您需要在设置城市之前选择适当的地址,而不是如上所述的简单分配,您需要添加它顺序。