Base solution for your next web application
Open Closed

Multiple DbContext #4160


User avatar
0
verrrrrrrrrrrrrdi created

Hi,

I have 2 dbcontext .

FirstDbContext

public class FirstDbContext : AbpZeroDbContext<Tenant, Role, User>
        {
            public virtual IDbSet<ModelA> ModelAs { get; set; }
        }

        public FirstDbContext()
            : base("Default")
        {

        }

        public FirstDbContext(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {

        }

        public FirstDbContext(DbConnection existingConnection)
           : base(existingConnection, false)
        {

        }

        public FirstDbContext(DbConnection existingConnection, bool contextOwnsConnection)
            : base(existingConnection, contextOwnsConnection)
        {

        }

SecondDbContext

public class SecondDbContext : AbpZeroDbContext
        {

            public virtual DbSet<ModelB> ModelAs { get; set; }
        }

        public SecondDbContext()
            : base("SecondDbContext")
        {

        }

When i use linq to join model a and model b like this:

var q = (from a in _modelA.GetAll()
                     join b in _modelB.GetAll()
                     on a.modelCode equals b.modelCode
                     select a).ToList();

I has implement new EF transaction strategy in myProjectDataModule like this:

Configuration.ReplaceService<IEfTransactionStrategy, DbContextEfTransactionStrategy>(DependencyLifeStyle.Transient);

It show error message : The transaction passed in is not associated with the current connection. Only transactions associated with the current connection may be used.

Please help ...


3 Answer(s)
  • User Avatar
    0
    aaron created
    Support Team

    DbContextEfTransactionStrategy simply uses the same transaction for multiple DbContexts. You can't join entities from multiple DbContexts.

    For that specific query, you can do this:

    var bModelCodes = _modelB.GetAll().Select(b => b.modelCode).ToList();
    var aModels = _modelA.GetAll().Where(a => bModelCodes.Contains(a.modelCode)).ToList();
    
  • User Avatar
    0
    verrrrrrrrrrrrrdi created

    Hi @aaron,

    How about if i want to get all data based on filter on modelB? Your solution is not good because i have to get all data from model A first. This is so dangerous solution if modelA have 1,000k more record.

    Do you have other solution to implement join entities on multiple dbcontext? please help

  • User Avatar
    0
    aaron created
    Support Team

    Your solution is not good because i have to get all data from model A first.

    What do you mean? That's what your code does.

    Do you have other solution to implement join entities on multiple dbcontext?

    Maybe you can use a stored procedure and a linked server, but I can't help with that.