简体   繁体   中英

Hard Coding the Connection String in Entity Framework

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM