【发布时间】:2016-02-19 11:40:44
【问题描述】:
我正在查询存储库以获取 Customer 对象的列表,但在返回的列表上调用 ToObservableCollection() 时遇到错误。
具体的错误是当我调用QueryDataFromPersistence()是:
'System.Collections.Generic.List<MongoDBApp.Models.CustomerModel>' does not contain a definition for 'ToObservableCollection' and no extension method 'ToObservableCollection' accepting a first argument of type 'System.Collections.Generic.List<MongoDBApp.Models.CustomerModel>' could be found
通过谷歌搜索错误,它指出这是一个错误,因为分配的列表和返回的列表不匹配。但是通过检查我的 CustomerRepositury 和 MainViewModel,两个列表是相同的。
我还检查了 Customer 模型和 MainViewModel 是否实现了它们所做的 INotifyPropertyChanged。
有人知道如何进一步调试吗?
在MainModel中,列表定义如下,QueryDataFromPersistence()被调用:
public ObservableCollection<CustomerModel> Customers
private void QueryDataFromPersistence()
{
Customers = _customerDataService.GetAllCustomers().ToObservableCollection();
}
在 DataService 类中,GetAllCustomers() 被调用:
ICustomerRepository repository;
public List<CustomerModel> GetAllCustomers()
{
return repository.GetCustomers();
}
之后,在 DataRepository 类中,GetCustomer() 被调用:
private static List<CustomerModel> customers = new List<CustomerModel>();
public List<CustomerModel> GetCustomers()
{
if (customers == null)
LoadCustomers();
return customers;
}
private void LoadCustomers()
{
var client = new MongoClient(connectionString);
var database = client.GetDatabase("orders");
//Get a handle on the customers collection:
var collection = database.GetCollection<CustomerModel>("customers");
try
{
customers = collection.Find(new BsonDocument()).ToListAsync().GetAwaiter().GetResult();
}
catch (MongoException ex)
{
//Log exception here:
MessageBox.Show("A connection error occurred: " + ex.Message, "Connection Exception", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
还有Customer 模型类:
public class CustomerModel : INotifyPropertyChanged
{
private ObjectId id;
private string firstName;
private string lastName;
private string email;
[BsonElement]
ObservableCollection<CustomerModel> customers { get; set; }
/// <summary>
/// This attribute is used to map the Id property to the ObjectId in the collection
/// </summary>
[BsonId]
public ObjectId Id { get; set; }
[BsonElement("firstName")]
public string FirstName
{
get
{
return firstName;
}
set
{
firstName = value;
RaisePropertyChanged("FirstName");
}
}
[BsonElement("lastName")]
public string LastName
{
get
{
return lastName;
}
set
{
lastName = value;
RaisePropertyChanged("LastName");
}
}
[BsonElement("email")]
public string Email
{
get
{
return email;
}
set
{
email = value;
RaisePropertyChanged("Email");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
【问题讨论】:
标签: c# list mvvm observablecollection assign