Entity Framework Core - Best way to access a collection on an entity?

后端 未结 2 929
[愿得一人]
[愿得一人] 2021-01-21 20:34

I have a simple ASP.NET Core 2.0 + Entity Framework Core project:

I have an entity called ApplicationUser, which extends Microsoft.AspNet.Identity.Ide

2条回答
  •  [愿得一人]
    2021-01-21 21:13

    Adding an answer here for EF Core 2.1 (Identity 4+).

    This answer is based on Lazy Loading. For other ways, see the end of the post.

    Tseng made a comment on the question, and at the time it was for EF 2.1 preview. 2.1 is RTM now, and that same link he posted is really your answer, if you upgrade to EF Core 2.1.

    It's really easy to use too. Following the direction for Lazy Loading with Proxies on the same link Tseng mentioned, you basically do this (assuming you've got your models defined properly with 'virtual' as per the link says):

    1. Install the Nuget package Microsoft.EntityFrameworkCore.Proxies.
    2. In your .AddDbContext<...>(...) or in your OnConfiguring(), add a call to .UseLazyLoadingProxies() For example, in Startup.cs:

          services.AddDbContextPool(options =>
                  options.UseMySql(Configuration.GetConnectionString("ApplicationDbContext"))
                         .UseLazyLoadingProxies()
      
          );
      

    Rebuild. That's it. There are other ways mentioned too besides using Proxies, but this is the simplest.

    To retrieve data using this:

    var user = await _userManager.GetUserAsync(ApplicationUser);
    var addresses = user.UserAddresses;
    

    with models similar to:

    public class ApplicationUser : IdentityUser
    {
        public ApplicationUser()
        {
            UserAddresses = new List();
        }
    
        public virtual ICollection UserAddresses { get; set; }
    }
    
    public class UserAddress
    {
        public int UserAddressId { get; set; }
        public int Id { get; set; }
        ...
        public virtual ApplicationUser User { get; set; }
    }
    

    If you prefer to use Eager Loading or Explicit Loading, the same link has the details. I just do not go over them here.

提交回复
热议问题