Bright load using LINQ to SQL with Include ()

I spent 2 days stumbling on this problem, and I can’t crack it (such a problem). The same code worked fine until I added a relationship to the database, and since then I read a lot about lazy loading.

I have two database tables with a 1: 1 ratio between them. PromoCodetable track codes and a PK column with a name id. The table CustomerPromohas a column PromoIdthat is associated with the table PromoCode id. These two tables have no other relationship. I created all of this in SQL Server Management Studio, and then generated the model from the database.

To make things a bit more complicated, I do this in the WCF data service, but I don't think this should matter (it worked before adding database connections). After enabling logging, I always get an exception in the log file with the text:

Access to the DataContext after Dispose.

My function currently returns all records from a table:

using (MsSqlDataContext db = new MsSqlDataContext())
{
    // This causes issues with lazy-loading
    return db.PromoCodes.ToArray();
}

I have read many articles / pages / answers and they all say they use the method .Include(). But this does not work for me:

return db.PromoCodes.Include(x => x.CustomerPromos).ToArray();

I also tried the magic string version:

return db.PromoCodes.Include("CustomerPromos").ToArray();

The only code I managed to get is:

PromoCode[] toReturn = db.PromoCodes.ToArray();

foreach (var p in toReturn)
    p.CustomerPromos.Load();

return toReturn;

.Where(), .Select(), .Include() .Where() ( , , , - ). , .Include() , .

? ? ? "" , Include (.. CustomerPromo Customer).

Edit
. - LINQ to SQL, WCF. , :

[WebGet]
[OperationContract]
public PromoCode[] Test()
{
    using (MsSqlDataContext db = new MsSqlDataContext())
    {
        return db.PromoCodes.Include(x => x.CustomerPromos).ToArray();
    }
}

(, http://<address>:<port>/DataService.svc/Test), reset WCF, "DataContext accessed after Dispose.". AJAX -, AJAX error ( !).

+4
2

, - . , .

, , , . , , .Include() ( Including(), , ) , DataLoadOptions. , .

DeferredLoadingEnabled. , :

using (MsSqlDataContext db = new MsSqlDataContext())
{
    DataLoadOptions options = new DataLoadOptions();
    options.LoadWith<PromoCode>(p => p.CustomerPromos);
    db.LoadOptions = options;

    return db.PromoCodes.ToArray();
}

Unidirectional Serialisation DeferredLoadingEnabled = false;.

+3

: . , . parent, . . .

, , .Include(), .

using (MsSqlDataContext db = new MsSqlDataContext())
{
    db.DeferredLoadingEnabled = false; // THIS makes all the difference
    return db.PromoCodes.ToArray();
}

, ( @Virgil), . LazyLoadingEnabled LINQ to SQL ( EntityFramework). , LINQ to SQL DeferredLoadingEnabled.

MSDN DeferredLoadingEnabled.

+1

Source: https://habr.com/ru/post/1622668/


All Articles