2013-12-13 135 views
-2

假设我有一类叫做客户(通过实体框架自动生成)检查对象为空

CustomerID // Primary Key & Auto-increment 
Name 
Gender 
City 

现在在我的视图模型:

public Class myViewModel : INotifyPropertyChanged 
{ 
    public Customer CurrentCustomer 
    { 
     get 
     { 
      return MainViewModel.cCustomer; 
     } 
     set 
     { 
      myViewModel.cCustomer = value; 
      OnPropertyChanged("CurrentCustomer"); 
     } 
    } 

    .... 
    .... 
    .... 

} 

这里是我的MainViewModel

public Class MainViewModel : INotifyPropertyChanged 
{ 
    public MainViewModel() 
    { 
     cCustomer = new Customer(); 
    } 

    public static Customer cCustomer { get; set; } 

    public void SaveChanges() 
    { 
     //Here I want to check if all the fields of cCustomer are empty 
     //And depending on that I want to save the cCustomer. 
    } 

    .... 
    .... 
    .... 

} 

我试图通过将它们与null比较来检查cCustomer的所有字段,但是在那里我得到一个错误,指出对象引用没有设置为对象的实例。

总之,我想在保存客户时检查cCustomer是否为空。

+3

'if(cCustomer!= null)'不起作用? – Tim

+1

附加调试器,看看什么是空? –

+0

cCustomer是否曾实例化或初始化? –

回答

1

MainViewModel类声明cCustomer属性为静态的,而是你设置在类的构造函数该属性:

public Class MainViewModel : INotifyPropertyChanged 
{ 
    public MainViewModel() 
    { 
     cCustomer = new Customer(); 
    } 

    public static Customer cCustomer { get; set; } 

正因为如此,当您试图访问静态这些线路cCustomer属性,它可能不被填充:

get 
{ 
    // Unless you've created an instance of a MainViewModel already, 
    // this property will be null 
    return MainViewModel.cCustomer; 
} 
set 
{ 
    myViewModel.cCustomer = value; 
    OnPropertyChanged("CurrentCustomer"); 
} 

你真的希望cCustomer属性是静态的吗?另外,在一个实例构造函数中为一个类设置静态属性可能是一种不好的做法,应该避免。

+0

我已将该成员设为静态,因为我想在myViewModel中访问我的Mainviewmodel的当前实例。如果有任何方法访问mainViewModel的当前实例,那么请建议。 – Khushi

0

这可能是你的cCustomernull(有一个在属性集没有验证) - 很容易,虽然检查:

if (cCustomer == null) 
{ 
    // No Customer record, so don't even think about checking properties on it. 
    // feel free to throw an exception if it's not valid to save without one... 
} 
+0

它并不那么容易。我在MainViewModel的构造函数中调用'cCustomer = new Customer()',就像我在我的问题中提到的那样。所以,cCustomer将永远不会为空。 – Khushi

+0

虽然它可以为null,例如:var model = new MainViewModel(); model.cCustomer = null;'。当然,你的调试器是一个非常棒的工具,用于检查什么是空的,并且在它变成这样的时候设置断点。 –

0

不要做,有......那应该是你的一部分数据模型。如果你的要求是不应该有null值,然后做使得在该类物业级别:

public string Text 
{ 
    get { return text; } 
    set { if (value != null) { text = value; NotifyPropertyChanged("Text"); } } 
} 
+0

我的要求不是不应该有空值。我想深入解释你的问题。我的项目中有15页。在mainwindow中,我有一个框架和一个菜单,所以用户可以从一个页面导航到另一个页面,他们可能会填充一些页面中的值,甚至可能无法打开某些页面。当用户完成后,他/她必须点击保存按钮,这是保存更改的唯一方法,并且该按钮位于我的主窗口上。 – Khushi