How to create an EntityConnection
I have a Solution with multiple projects.
One project is my DataAccess project with 2 SQL CE databases defined, one for local users and one for company data, both with similar table structures. Public, static, readonly strings are defined for each database, and connections can be made.
Another project is my WPF project that will (eventually) display my data. To display data here, I have tried creating an Entity Context object, but nothing seems to work.
What is preventing me from accessing my data in the other project? (Currently, error states 'data source' is not defined)
How do I fix it?
AbcEntities abcContext;
public MainWindow() {
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e) {
try {
EntityConnection ec = new EntityConnection(DataClass.AbcConnectionString);
abcContext= new AbcEntities(ec);
listbox1.ItemsSource = from c in abcContext.Customers select c;
abcCustomersBox.DisplayMemberPath = "Name";
} catch (Exception err) {
MessageBox.Show(err.Message开发者_如何学Go);
}
}
For others, I found out how to do this.
In my static DataClass, I created the following routine to generate the Entity Connection String for me:
static string BuildEntityConnString(string dbFileName, string resourceData, string password) {
string resAll = @"res://*/";
string dataSource = @"Data Source=|DataDirectory|\" + dbFileName;
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.Metadata = string.Format("{0}{1}.csdl|{0}{1}.ssdl|{0}{1}.msl", resAll, resourceData);
entityBuilder.Provider = "System.Data.SqlServerCe.3.5";
if (String.IsNullOrEmpty(password)) {
entityBuilder.ProviderConnectionString = dataSource;
} else {
entityBuilder.ProviderConnectionString = dataSource + ";Password=" + password;
}
using (EntityConnection con = new EntityConnection()) {
try {
con.ConnectionString = entityBuilder.ToString();
con.Open();
Console.WriteLine("{0} Entity String created.", dbFileName);
con.Close();
return con.ConnectionString;
} catch (Exception err) {
Console.WriteLine(err);
}
}
return null;
}
Notice that if there is any error, a NULL String is returned.
If anyone wants to use this, they should either place a breakpoint at the Exception, throw it, or handle it in some way. The Console.WriteLine()
was just for me to debug through this.
I created Entity Connection Strings for my applications as follows:
public static readonly string EntityConnString =
BuildEntityConnString("sqlCeDb.sdf", "myModel", "abc123~Funky");
Hope others get some mileage out of this.
Explanation (more of an example, really) of how to create an EntityConnection can be found on MSDN here:
http://msdn.microsoft.com/en-us/library/bb738533.aspx
Looks pretty similar to what you have.
精彩评论