开发者

Failover connection string in n-tier linq2sql

开发者 https://www.devze.com 2023-03-14 06:36 出处:网络
Scenario: ASP.Net web app (n-tier linq2sql) on local IISwith connection to SQL 2008 database over VPN.Some data is replicated to a local SQL 2008 express DB (different name).If the connection is down

Scenario: ASP.Net web app (n-tier linq2sql) on local IIS with connection to SQL 2008 database over VPN. Some data is replicated to a local SQL 2008 express DB (different name). If the connection is down to VPN database, we would like to use the local instance for some parts of the web app.

My Question is, how can the following solution be improved. we have involves a lot of passing the connection string about. If this involved mirroring, we could set the failover part开发者_如何学Goner but as it is a different database I don't think this is possible.

Current Code:

Check if we can connect remotely, put the working connection string in session

Session_Start()
{
//if can connect to remote db
Session["ConnStr"] = //remote connection
//else
Session["ConnStr"] = //local connection
}

Pass connection string in UI to BLL

        protected void ods1_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
    {
        TestManager myTestManager = new TestManager(Session["ConnString"].ToString());
        e.ObjectInstance = myTestManager;
    }

Pass to DAL

    public class TestManager
{
       private readonly string _connectionString;

       public TestManager(string connectionString)
    {
        _connectionString = connectionString;
    }
    [DataObjectMethod(DataObjectMethodType.Select, true)]
    public List<Test> GetAll()
    {
        TestDB testDB = new TestDB(_connectionString);
        return testDB.GetAll();
    }
}

Set connection in DAL creating DataContext in constructor

public class TestDB
{
    public TestDB(string connectionString)
    {
        _connectionString = connectionString;
        _dbContext = new TestDataContext(_connectionString);
    }
    private TestDataContext _dbContext;

    private string _connectionString;

    public string ConnectionString

    {
        get
        {
            return _connectionString;
        }
        set
        {
            _connectionString = value;
        }
    }

    public TestDataContext DbContext
    {
        get
        {
            return _dbContext;
        }
        set
        {
            _dbContext = value;
        }
    }

    public List<Test> GetAll()
    {
        var query = from t in DbContext.Tests
                    select new DTO.Test()
                    {
                        Id = t.Id,
                        Name = t.Name

                    };

        return query.ToList();


    }
0

精彩评论

暂无评论...
验证码 换一张
取 消