Remove relationships in select LINQ

3

My question is the next one, when executing this sentence in LINQ, it brings me the user that I require, but also all the table relations where it has been referenced by a foreign key in the DB, that is, if this user made 1000 sales are going to be linked those sales to the object usuario.sales.

usuario = (from u in db.Usuario
    where u.UsuarioId == this.Id
    select u).FirstOrDefault();

What I need is to remove the relationships that the user table has, or in other words, only obtain the data from the user table and not the other tables that have linked to it.

    
asked by jczarco 19.03.2018 в 15:19
source

3 answers

2

One serious option is not to create the navigation properties as virtual. This will use Eager Loading mode

When you want to use Lazy Loading then use virtual.

Example eager loading:

// Usuario
public class Usuario
{
    public int Id { get; set; }
    public Nombre { get; set; }
    public List<Factura> Facturas { get; set; }
}

// Factura
public class Factura
{
    public int Id { get; set; }
    public UsuarioId{ get; set; }
    public Usuario Usuario { get; set; }
}

You should also use Include () whenever you want some navigation property.

db.Usuario.Include(f => f.Facturas).ToList();

// Tambien lo puedes hacer de la siguiente manera
db.Usuarios.Include("Facturas").ToList();

To access the User through the invoice would be in reverse:

db.Facturas.Include(u => u.Usuario);

// O de la siguiente manera
db.Facturas.Include("Usuario");

To disable Lazy Loading globally

public class TuContext : DbContext
{
    public TuContext() : base("SQLConexion")
    {
        // inhabilita Lazy Loading de manera global
        Configuration.LazyLoadingEnabled = false; 
    }
}

I hope it serves you.

    
answered by 19.03.2018 / 16:00
source
2

This happens because you have Lazy Loading configured in entity framework, this causes the entities related to your object to load. In the constructor of your context you can disable it through the property LazyLoadingEnabled in Configuration

Configuration.LazyLoadingEnabled = false;

for example

public partial class TuContexto : DbContext
{
    public TuContexto() : base("cnn")
    {
        Configuration.LazyLoadingEnabled = false;
    }
}

Then if in another query you want to obtain sales or other navigation property, you use the Include()

method

for example

db.Usuario.Include(p => p.ventas).ToList();

remember that Include is a DbSet method

greetings

    
answered by 19.03.2018 в 15:34
1

You must turn off the DeferredLoadingEnabled that by default is on.

        //.....

        using(var db = new DBDataContext())
        {
            db.DeferredLoadingEnabled = false;

            //TODO: query here.....
        }


        //.....
    
answered by 19.03.2018 в 15:44