0

I created a EDMX file from DB:

internal partial class LocalBDD : DbContext
{
    public LocalBDD() : base("name=LocalBDD")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<C__RefactorLog> C__RefactorLog { get; set; }
}

If I store the connection string in App.config, this works fine, but I need to encrypt the sensitive info, I'm trying to change the connection from my context in this way:

LocalBDD _localBDD;
_localBDD = new LocalBDD("my new connStr");

But I get

LocalBDD does not contain a constructor that takes 1 arguments

This code it's generated by the ADO.NET Entity Data Model Assitant, and if I edit it for add a constructor which takes 1 argument, when the project recompile the changes will be lose.

How I can change the connection string of my DbContext at runtime?

Thanks in advance

1

2 Answers 2

2

I highly recommend that you read some basic C# tutorials on classes and constructors, which would help you understand the error you are receiving.

Your LocalBDD class constructor only takes one argument. If you want to be able to pass in connection string information, you need to either expand your current constructor or add an additional constructor with a string argument:

public LocalBDD()
    : base("name=LocalBDD")
{
}

public LocalBDD(string connectionString)
    : base(connectionString)
{
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I think it raises my question wrong, I really want to know why the assistant visual studio generates this code, when compiling rewrites and does not retain changes.
0

Based on David's response I created a separate .cs file and wrote in this a partial class to prevent the overwriting:

public partial class LocalBDD : DbContext
{
    public LocalBDD(string connetionString)
        : base(connetionString)
    {
    }
}

However I´m not sure this is the better way. Thanks to both of you.

1 Comment

Using partial class is the best way to do this, as the 2 files would be merged together into a single file at runtime, so you have the 2 constructors in a single file. Visual studio make changes to the generated dbContext class every time you update your context and any changes to the dbContext class will be wiped out. So creating a partial class prevents you from losing the changes you made

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.