I am working on a project where we use EF for data access and WPF and MVVM for user interface.
I am binding a view model to the data context of a window. This view model has a default constructor defined as following:
public KonumVM()
{
LocationOperations = new LocationOperations();
LocationNames = new ObservableCollection<string>();
Corporations= new ObservableCollection<Kurum>();
//Corporations= LocationOperations.GetCorpValues();
//foreach (var corp in Corporations)
//{
// LocationNames.Add(corp.Name);
//}
}
The commented lines are where I query the database. If the lines are not commented, when I try to edit the XAML code of the window that binds to this View Model I get an exception, I think it is a XAML Load Failure, which blocks designer. The exception is at the end of the message. When I comment the database querying lines, the designer is fine, no exceptions.
What should I do? Should I move the database access code to some other place other than default constructor?
Cannot open database “DemirbaşEntityLibrary.DemirbaşContext” requested
by the login. The login failed. Login failed for user ‘Rfid\Mert’.
at
System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection
owningObject) at
System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection
owningConnection) at
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection
outerConnection, DbConnectionFactory connectionFactory) at
System.Data.SqlClient.SqlConnection.Open() at
System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean
openCondition, DbConnection storeConnectionToOpen, DbConnection
originalConnection, String exceptionCode, String attemptedOperation,
Boolean& closeStoreConnectionOnFailure)
The solution came by moving my context binding code to code-behind file, so XAML parser does not try to access DB while I am designing the UI.
If you don’t like the code-behind approach (for some reason), you can move it back to your XAML code when you finish designing UI.