Hard Coding the Connection String in Entity Framework

空扰寡人 提交于 2020-01-25 21:56:10

问题


I know that a lot of people think it is a bad idea to hard code connection info but I have a specific situation where I need to do it. Please don't downtick me because you think this is a bad idea - again, very specific circumstance.

Using the code below, I get the following error on the LINQ statement: The underlying provider failed on Open. I have tested the connection string independently and I have no trouble connecting with it.

public partial class Form1 : Form
{
    public Form1()
    {
       InitializeComponent(); 

        var entityConnectionStringBuilder = new EntityConnectionStringBuilder();
        entityConnectionStringBuilder.Provider = "System.Data.SqlClient";
        entityConnectionStringBuilder.ProviderConnectionString = "Data Source=DESKTOP-A43456\\MAIN;Initial Catalog=MAIN;Persist Security Info=True;User ID=AppUser;Password=3092409SALFKJ93LK342";
        entityConnectionStringBuilder.Metadata = "res://*";


        MyEntities CustContext = new MyEntities(entityConnectionStringBuilder.ToString());

        var q = (from i in CustContext.Customers
                 where i.fid3 == 15
                 select new CustClass
                 {
                     fid1 = i.fid1,
                     fid2 = i.fid2,
                     fid3  = (int)i.fid3
                 }).ToList<CustClass>();

    }
} 

Thank you in advance for any help and insight you can provide. I did look at other relevant posts and tried various changes on Metadata but they did not work.


回答1:


Given the class definition you've shared in the comments, your problem lies with the Entities class.

Its constructor should pass the connection string to the DbContext base class constructor:

public Entities(string nameOrConnectionString) : base(nameOrConnectionString) {}

All the best with your project!



来源:https://stackoverflow.com/questions/44122708/hard-coding-the-connection-string-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!