0

I am working on a project which is functioning on .netframework 4.6, VS 2015, EntityFramework 6.x

I am trying to connect to more than one database which are in different database servers.

My dabatase looks like :

enter image description here

I have a main project and repository project which is a class library.

my proj structure : enter image description here

In my repository project I added two EntityFramework models namely CompanyEmployeeModel.edmx and MultipleTestModel.edmx.

In My EmployeeDAL.CS :

private static async Task<string> GetCompanyInformationByIdCompany(int idCompany)
        {
            string result = string.Empty;

            try
            {
                using (var db = new Entities())
                {
                    var companyInformation = await db.CompanyInformations.Where(x => x.id == idCompany).FirstOrDefaultAsync();
                    result = companyInformation.name;
                }

 using (var dbTest = new fccidevEntities())
                    {
                        var EmployeeInformation = await dbTest.Employees.Where(x => x.Id == 10).FirstOrDefaultAsync();
                        //result = EmployeeInformation..name;
                    }
            }
            catch
            {
                result = string.Empty;
            }

            return result;
        }

Is this the right way of doing. Can somebody suggest how to connect to multiple databases residing in multiple servers.

Exception :

enter image description here

2
  • just use mutlipe connection strings: stackoverflow.com/questions/24769451/… Commented May 20, 2016 at 21:29
  • I agree with bateloche comment below. However, if you dont have time to refactor your model, you can always pass in the connection string to the dbcontext. Commented May 20, 2016 at 21:33

1 Answer 1

2

With EF you'll need two contexts, there's no way of getting rid of this, what I would do in your case is to have something encapsulating the contexts.

This way you'll have not to worry what database are you acessing at this moment.

Just be aware that for most requests you'll open two differente connections and that comes at a cost, you'll have more network IO and memory load than a single database application.

Sign up to request clarification or add additional context in comments.

5 Comments

an example please. by the way I am getting the following error. Invalid object dbo.Employees. Employees is a table in fccidev.
is the schema dbo? post your exception details so we know what's happening.
added a screenshot of the exception.
check the sql query being executed.
it may be wrong connection string, check also if EF's running the query on the right database.

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.