这是我到目前为止所拥有的:
<add name="gymEntities1" connectionString="metadata=res://*/DateModel.csdl|res://*/DateModel.ssdl|res://*/DateModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=gym;user id=sa;password=xxxx;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
它可以在我的LocalHost数据库上运行,并且可以从中加载数据。 但是,我有一台服务器,在上面安装了数据库的sqlserver,基本上是当我更改连接字符串的sqlcommands这项工作时,但是在程序的某些部分中,我使用了实体框架,却不知道如何更改它的连接字符串,有些帖子在stackoverflow中,我将其更改为
<add name="gymEntities2" connectionString="metadata=res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=tcp:46.105.124.144;initial catalog = gym ;User ID=sa;Password=xxxx"" providerName="System.Data.EntityClient" />
,但是它仍然从本地主机读取数据,并且未连接到服务器。 我不知道如何将连接字符串更改为服务器时仍从本地数据库读取数据。
从App.Config更改连接字符串的最佳方法是什么?
答案 0 :(得分:3)
可能性较小,因为其他人向您提出了建议。但是,您可能会丢失web.config或app.config中的一个连接字符串。 将字符串复制到每个项目是一个好习惯。例。我的解决方案中有3个不同的项目(库,WCF,WPF)。我将以下连接字符串复制到每个项目(一个示例用于Local SQL Server,另一个示例用于Azure ):
<connectionStrings>
<add name="LocalSQLServerSample.CodeREDEntities" connectionString="metadata=res://*/CodeRED.csdl|res://*/CodeRED.ssdl|res://*/CodeRED.msl;provider=System.Data.SqlClient;provider connection string="data source=MachineName\ServerName;initial catalog=CodeRED;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="AzureSQLServerSample.CodeREDEntities" connectionString="metadata=res://*/CodeRED.csdl|res://*/CodeRED.ssdl|res://*/CodeRED.msl;provider=System.Data.SqlClient;provider connection string='data source=azureservername.database.windows.net;initial catalog="CodeRED";persist security info=True;user id=CodeRED;password=R%Chd$g*VHs28eEr;MultipleActiveResultSets=True;App=EntityFramework'" providerName="System.Data.EntityClient" />
</connectionStrings>
您已经提到您正在使用实体框架。您是否正在使用ObjectContext进行访问?如果是,则每次访问任何数据库时,我都有以下方法来调用它:
来自上面的示例: name =“ LocalSQLServerSample.CodeREDEntities”
_containerName 是CodeREDEntities(我的所有连接都相同)。 环境用于确定您要连接到的数据库。例如,在上面的连接示例中,我有 LocalSQLServerSample 和 AzureSQLServerSample ,通常我会使用 PRODUCTION , DEVELOPMENT >,测试 ....
public static ObjectContext getObjectContext(string environment, bool isReadOnly)
{
environment = environment == null ? "" : environment.Trim();
environment = environment.Length == 0 ? "" : (environment + ".");
ObjectContext objectContext = new ObjectContext(
ConfigurationManager.ConnectionStrings[environment + _containerName].ToString());
objectContext.DefaultContainerName = _containerName;
objectContext.CommandTimeout = 0;
objectContext.ContextOptions.ProxyCreationEnabled = !isReadOnly;
return objectContext;
}
使用方法示例:
公共是我用来存储共享信息的公共类,例如获取用于Common.getInnerExceptionMessage的公共错误格式。
此外,您不必总是传递环境,您可以将其存储为常量以能够调用它,例如(我总是传递它以在需要进行特定调用时能够混合连接):如果您不希望将连接传递到任何地方,则可以通过更改 _selectedEnvironment 来从任何地方修改连接。
public const string _ENVIRONMENT_DEVELOPMENT = "LocalSQLServerSample";
public const string _ENVIRONMENT_PRODUCTION = "AzureSQLServerSample";
public static string _selectedEnvironment = _ENVIRONMENT_PRODUCTION;
根据ID获取商品的示例:
注意:用户是实体框架从数据库生成的类。
public UsersDataGrid GetItem(string environment, long id)
{
ObjectContext objectContext = Common.getObjectContext(environment, false);
try
{
var item = objectContext.CreateObjectSet<User>()
.Where(W => W.ID == id)
.Select(S => new UsersDataGrid()
{
Active = S.Active,
ID = S.ID,
Unique_ID = S.Unique_ID,
First_Name = S.First_Name.ToUpper(),
Last_Name = S.Last_Name.ToUpper(),
Email = S.Email,
School = S.School.Title.ToUpper(),
Gender = S.Gender.Title.ToUpper(),
TShirt_Size = S.TShirt_Size.Title.ToUpper(),
GUID = S.GUID + "",
Note = S.Note,
Machine_User = S.Machine_User,
Machine_Name = S.Machine_Name,
Created_On = S.Created_On,
Last_Updated_On = S.Updated_On
}).FirstOrDefault();
return item;
}
catch (Exception exception)
{
return new UsersDataGrid()
{
Note = ("Service Error: " +
Common.getInnerExceptionMessage(exception))
};
}
}
第二个示例:更新用户:
注意: Common.CopyValuesFromSourceToDestinationForUpdate 只是将项目从 item 对象复制到 entityItem 的通用方法,而您可以正常复制诸如 entityItem.ID = item.ID ,依此类推...
public Result Update(string environment, User item)
{
ObjectContext objectContext = WCF_Service_Library.Classes.Common.getObjectContext(environment, false);
try
{
var entityItem = objectContext.CreateObjectSet<User>()
.AsEnumerable().Where(Item => Item.ID == item.ID).ToList().FirstOrDefault();
if (entityItem == null)
return new Result("Item does NOT exist in the database!");
entityItem = Common.CopyValuesFromSourceToDestinationForUpdate(item, entityItem) as User;
objectContext.SaveChanges();
return new Result(entityItem.ID);
}
catch (Exception exception)
{
return new Result("Service Error: " + Common.getInnerExceptionMessage(exception));
}
}
如果您发布应用程序并且仅对WPF项目进行签名,则在发布过程中不会出现错误,但是您可能无法连接到数据库。您必须在解决方案中签署所有项目。
希望这可以帮助您解决问题
答案 1 :(得分:1)
检查启动项目的WebConfig
。运行ConnnectionString
操作时,实体框架会从AppConfig
中读取Update Model From Db
。
但是在运行时,它会从您的启动项目中的ConnnectionString
中读取WebConfig
答案 2 :(得分:1)
I hope it is use for you
Add this for App.Config files
<connectionStrings>
<add name="Dbconnection"
connectionString="Server=localhost; Database=OnlineShopping;
Integrated Security=True"; providerName="System.Data.SqlClient" />
</connectionStrings>
答案 3 :(得分:0)
此连接字符串必须有效:
<add name="Name"
connectionString="metadata=<Conceptual Model>|<Store Model>|<Mapping Model>;
provider=<Underlying Connection Provider>;
provider connection string="<Underlying ConnectionString>""
providerName="System.Data.EntityClient"/>
如果您在编写连接字符串时遇到任何问题,可以在the page上使用以下代码。
答案 4 :(得分:0)
这就是我到目前为止在等待中所遇到的事情
public async Task GetAccounts()
{
MainWin w = new MainWin();
await Task.Run(() =>
{
this.Dispatcher.Invoke(() =>
{
using (SqlConnection connection = new SqlConnection(PublicVar.ConnectionString))
{
gymEntities2 database = new gymEntities2();
SqlConnection con1 = new SqlConnection(PublicVar.ConnectionString);
PublicVar.TodayTime = String.Format("{0:yyyy/MM/dd}", Convert.ToDateTime(TimeNow.Text));
con1.Open();
SqlCommand Actives = new SqlCommand("Select DISTINCT (LockEndDate) from LockTable Where Username = '" + txt_username.Text + "' and Password = '" + txt_password.Password + "'", con1);
object Active = Actives.ExecuteScalar();
string SystemActive = Convert.ToString(Active);
// SqlCommand Commandcmds = new SqlCommand("update VW_TimeOut set UserActive = 2 where UserEndDate < '" + String.Format("{0:yyyy/MM/dd}", Convert.ToDateTime(TimeNow.Text)) + "'", con1);
// Commandcmds.ExecuteScalar();
SqlCommand Commandcmd = new SqlCommand("SELECT COUNT(*) FROM LockTable Where Username = '" + txt_username.Text + "' and Password = '" + txt_password.Password + "' and LockEndDate between '" + String.Format("{0:yyyy/MM/dd}", Convert.ToDateTime(Lock.Text)) + "' And '" + SystemActive + "'", con1);
int userCount = (int)Commandcmd.ExecuteScalar();
//Find Gym ID -> To Set Public Value Strings
SqlCommand FindGymID = new SqlCommand("Select DISTINCT (LockID) from LockTable Where Username = '" + txt_username.Text + "' and Password = '" + txt_password.Password + "'", con1);
object ObGymID = FindGymID.ExecuteScalar();
if (userCount > 0)
{
try
{
RegistryKey UsernameKey = Registry.CurrentUser.CreateSubKey("SOFTWARE\\GYM");
if (CheakRem.IsChecked == true)
if ((string)UsernameKey.GetValue("UserNameRegister") != "")
{
UsernameKey.SetValue("UserNameRegister", txt_username.Text.Trim());
UsernameKey.SetValue("PasswordRegister", Module.Decode.EncryptTextUsingUTF8(txt_password.Password.Trim()));
}
PublicVar.GymID = Convert.ToString(ObGymID);
login = true;
}
catch
{
w.Username = null;
w.Password = null;
}
}
else
{
ErrorPage pageerror = new ErrorPage();
pageerror.Show();
con1.Close();
w.Username = null;
w.Password = null;
}
con1.Close();
}
});
});
if (login == true)
{
w.Username = txt_username.Text;
w.Password = txt_password.Password;
w.Show();
this.Close();
}
}
#endregion
我的事件代码是
private async void btn_join_Click(object sender, RoutedEventArgs e)
{
await GetAccounts();
}
但是我的程序在被按下时将挂起,而没有等待工作。你知道为什么吗?