Home > Back-end >  Entity Framework ignore not included foreign keys
Entity Framework ignore not included foreign keys

Time:02-01

In my .net 6.0 project I use the Entity Framework 6 to get data from my database.

My model contains a foreign key, which is used to resolve the data of the id.

I use the following call to resolve the foreign key:

// ...
_context.Tools.Include(t => t.User).ToListAsync();
// ...

My Tool Model looks like this:

[Table("MY_TOOLS")]
public class Tool
{
    [Key]
    [Column("ID")]
    public int Id { get; set; }
    
    [Column("UPDATED_BY")]
    public int? UpdatedBy { get; set; }

    [ForeignKey("UpdatedBy")]
    public User? User { get; set; }
}

My User class looks like this:

[Table("MY_USERS")]
public class User
{
    [Key]
    [Column("ID")]
    public int Id { get; set; }
    [Column("EMAIL")]
    public string? Email { get; set; }
}

When I leave the include like described above, the user is resolved correctly.

Is there a way to remove the user property from the loaded data, when I don't explicitly tell the Model to resolve the foreign key?

CodePudding user response:

It shouldnt resolve it by default as it uses lazy loading. You would have to query it specifically for the user object to get it e.g. _context.My_Tools.include(uvar = uvar.User).FirstOrDefault();

So you just make a method called getToolEager() and one called getTool() it would be a "waste" of a call to query for the user object only to throw it away in case you might not need it.

CodePudding user response:

You have 2 options:

Lazy Loading Proxy

Use Lazy Loading as described here: https://learn.microsoft.com/en-us/ef/core/querying/related-data/lazy

After just load data as _context.Tools.ToListAsync(); and users will load when you try access them.

Manually load related data

Modify Tool to explicitly store User FK:

[Table("MY_TOOLS")]
public class Tool
{
    [Key]
    [Column("ID")]
    public int Id { get; set; }
    
    [Column("UPDATED_BY")]
    public int? UpdatedBy { get; set; }

    [ForeignKey("UpdatedBy")]
    public User? User { get; set; }
 
    public int? UpdatedBy{ get; set; }
}

So when you load data as _context.Tools.ToListAsync(); fieldUser will be null but UpdatedBy will have User Id(if FK is not null in DB), so you can manually load them manually like tool.User = await _context.Users.FirstOrDefaultAsync(t => t.Id == tool.UpdatedBy);

  • Related