我在尝试使用WP7上的LINQ向表中添加记录时收到NullReferenceException。我对C#/ LINQ比较陌生,所以我复制了一个现有的方法,但是现在我无法使它适用于新记录。代码如下;
private ObservableCollection<DBControl.Categories> _category;
public ObservableCollection<DBControl.Categories> Category
{
get
{
return _category;
}
set
{
if (_category != value)
{
_category = value;
NotifyPropertyChanged("Category");
}
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
string TestCategory = "Cars";
// Create a new to-do item based on the text box.
DBControl.Categories newCat = new DBControl.Categories { CategoryDesc = TestCategory };
//CategoryDesc
// Add a to-do item to the observable collection.
**Category.Add(newCat);**
// Add a to-do item to the local database.
BoughtItemDB.Category.InsertOnSubmit(newCat);
BoughtItemDB.SubmitChanges();
}
给我错误的代码行是 Category.Add(newCat)
据我所知,一切看起来都不错,这可能意味着我犯了一个愚蠢的错误(再次)。
非常感谢任何帮助。
表格定义如下;
[Table(Name = "Categories")]
public class Categories : INotifyPropertyChanged, INotifyPropertyChanging
{
// Define ID: private field, public property and database column.
private int _categoryId;
[Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
public int CategoryId
{
get
{
return _categoryId;
}
set
{
if (_categoryId != value)
{
NotifyPropertyChanging("CategoryId");
_categoryId = value;
NotifyPropertyChanged("CategoryId");
}
}
}
// Define item category: private field, public property and database column.
private string _categoryDesc;
[Column]
public string CategoryDesc
{
get
{
return _categoryDesc;
}
set
{
if (_categoryDesc != value)
{
NotifyPropertyChanging("CategoryDesc");
_categoryDesc = value;
NotifyPropertyChanged("CategoryDesc");
}
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
// Used to notify the page that a data context property changed
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
#region INotifyPropertyChanging Members
public event PropertyChangingEventHandler PropertyChanging;
// Used to notify the data context that a data context property is about to change
private void NotifyPropertyChanging(string propertyName)
{
if (PropertyChanging != null)
{
PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
}
}
#endregion
}
答案 0 :(得分:2)
您需要初始化Category或_category。它没有设置为任何值,因此您尝试将Add()设置为未初始化的对象。