简体   繁体   中英

The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects Entity Framework

I have two classes generated from the database, and they interact with each other through many-to-many relationship. When I want to add a record in the many-to-many relationship table I get the following error: The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.

Entity Framework model diagram is the following:

在此输入图像描述

The function that adds the object, and works with DataContext :

public async Task AddInterakcijaAsync(Korisnik korisnik, Projekat projekat)
{
        using (ExtentBazaEntities _context = new ExtentBazaEntities())
        {
            _context.Korisnik.FirstOrDefault(a => a.KorisnickoIme == korisnik.KorisnickoIme).Projekat.Add(projekat);
            await _context.SaveChangesAsync();
        }
}

But the place where error pops up is when I call this function, the call of this function is next:

AddInterakcijaAsync(k, trenutniProjekat);

Avoid sending entities outside the boundary of their DbContext. The passed in Korisniko and Projekat were loaded from DbContext A. The method initiates DbContext B and loads the matching Korisniko, however it's attempting to associate the Projekat from DbContext A which it knows nothing about, but recognizes it as an EF entity tracked by another context.

I'd suggest updating your method signature to just accept the IDs since the method call encapsulates a DbContext to handle the insert.

public async Task AddInterakcijaAsync(int korisnikoIme, int projekatIme)
{
    using (ExtentBazaEntities _context = new ExtentBazaEntities())
    {
        var korisniko = _context.Korisnik.Single(a => a.KorisnickoIme == korisnickoIme)
        var projekat = _context.Projekat.Single(a => a.ProjekatIme == projekatIme);
        korisniko.Projekat.Add(projekat);
        await _context.SaveChangesAsync();
    }
}

Guessing at the ID names/types. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM