Hazem
Hazem

Reputation: 33

Using multiple contexts .Net core

My project depends on 2 different DB in 2 different projects and I want to make a join between 2 tables from each other and this my API code I've used

            var mBranch = (from Branch in _context.M_Branch.Where(p => p.BrnchNo == id)
                       join Dalel in _Erp_Context.Dalel on Branch.BrnchDebit equals Dalel.DalelNo into bt
                           from tt in bt.DefaultIfEmpty()
                           select new M_Branch
                           {
                               BrnchNo = Branch.BrnchNo,
                               BrnchCredit = Branch.BrnchCredit,
                               BrnchDalelDebit = tt.DalelDesc,
                               BrnchDebit = Branch.BrnchDebit,
                               BrnchDalelCredit = tt.DalelDesc,
                               BrnchDesc = Branch.BrnchDesc,
                               BrnchNotice = Branch.BrnchNotice,
                               BrnchUserNo = Branch.BrnchUserNo
                           }).FirstOrDefault();

but it says I can't use 2 different DB Context so I ended up with this solution I've found EntityFramework context across multiple projects or joining between two contexts

but it always gets me this error

System.NullReferenceException: Object reference not set to an instance of an object.

what's the solution and what's the best way to deal with Contexts more regularly and don't affect in memory or performance

Upvotes: 0

Views: 756

Answers (1)

Martin Staufcik
Martin Staufcik

Reputation: 9490

You might use a synonym in your database. You could create a synonym of Dalel table in _context database, or you could create M_Branch synonym in _Erp_Context, whichever makes more sense. Then you would be able to add these synonyme tables into your context in EF.

This post shows an example of using a synonym with EF: Entity Framework Code First with SQL Server Synonyms

Upvotes: 0

Related Questions