c# - 更改 Entity Framework 连接字符串到服务器

标签 c# wpf server

这是我目前所拥有的:

    <add name="gymEntities1" connectionString="metadata=res://*/DateModel.csdl|res://*/DateModel.ssdl|res://*/DateModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.;initial catalog=gym;user id=sa;password=xxxx;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

它适用于我的 LocalHost 数据库,我可以从中加载我的数据。 但是,我有一个服务器,在上面安装了 sqlserver 和我的数据库,基本上当我更改我的 sqlcommands 连接字符串时这项工作但在我程序的某些部分我使用了 Entity Framework 并且不知道如何更改它的连接字符串,有一些帖子在 stackoverflow 中,我将其更改为

    <add name="gymEntities2" connectionString="metadata=res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=tcp:46.105.124.144;initial catalog = gym ;User ID=sa;Password=xxxx&quot;" providerName="System.Data.EntityClient" />

但它仍然从我的本地主机读取数据并且没有连接到我的服务器。 我不知道当我将此连接字符串更改为我的服务器时,它仍然如何从我的本地主机数据库中读取数据。

从 App.Config 更改连接字符串的最佳方法是什么?

最佳答案

第一个可能的问题:

不太可能,因为其他人向您建议过。但是,您的 web.config 或 app.config 之一中可能缺少连接字符串。 将字符串复制到每个项目是一个好习惯。例子。我的解决方案中有 3 个不同的项目(库、WCF、WPF)。我将以下连接字符串复制到每个项目(本地 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=&quot;data source=MachineName\ServerName;initial catalog=CodeRED;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" 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=&quot;CodeRED&quot;;persist security info=True;user id=CodeRED;password=R%Chd$g*VHs28eEr;MultipleActiveResultSets=True;App=EntityFramework'" providerName="System.Data.EntityClient" />
</connectionStrings>

第二个可能的问题:

您提到您正在使用 Entity Framework 。您是否使用 ObjectContext 访问它?如果是,我有下面的方法可以在每次我想访问任何数据库时调用它:

来自上面的示例:name="LocalSQLServerSample.CodeREDEntities"

_containerName 是 CodeREDEntities(我所有的连接都一样)。 environment是判断你连接的是哪个数据库。例如,在上面的连接示例中,我有 LocalSQLServerSampleAzureSQLServerSample 并且我通常有类似PRODUCTIONDEVELOPMENT>, 测试....

    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 是我用来存储共享信息的通用类,例如获取用于 Common.getInnerExceptionMessage 的通用错误格式。

此外,您不必总是传递环境,您可以将其存储为常量以便能够调用它,例如(我总是传递它以便在需要特定调用时能够混合连接):如果您不想在任何地方传递它,您可以通过更改 _selectedEnvironment 从任何地方修改连接。

    public const string _ENVIRONMENT_DEVELOPMENT = "LocalSQLServerSample";
    public const string _ENVIRONMENT_PRODUCTION = "AzureSQLServerSample";
    public static string _selectedEnvironment = _ENVIRONMENT_PRODUCTION;

根据id获取item的示例:

注意:User是 Entity Framework 从数据库生成的类。

    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 项目,您将不会在发布过程中出现错误,但您可能无法连接到数据库。您必须在解决方案中签署所有项目。

希望这能帮助您解决问题

关于c# - 更改 Entity Framework 连接字符串到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53118386/

相关文章:

ios - 如何检查 Objective c 中是否没有服务器响应

mysql - 环回 : how do I make sure that values are sent to the local db, 不是远程数据库?

c# - 将运算符视为对象

c# - 存储库模式与 DTO 模式方法

c# - ChromeDriver 不记录日志

c# - 如何在 OpenNI kinect 中保存所有深度帧

wpf - 从 HierachicalDataTemplate 绑定(bind)到 TreeView 的 DataContext

c# - 是否可以将 WPF WebBrowser 与其他 UIElement 重叠?

terminal - 将目录从本地机器移动到服务器的 SCP 命令

c# - 在 C#.NET 中使用 USB PS2 手控器