简体   繁体   English

Microsoft.EntityFrameworkCore ProjectTo() 找不到我的存储库的方法定义

[英]Microsoft.EntityFrameworkCore ProjectTo() Method definition not found for my repository

I have just started working with databases and Entity Framework for the first time in C# and I am trying to get all the data out of my database right now but I can't seem to use the ProjectTo<T>() method in my method I am writing.我刚刚开始在 C# 中第一次使用数据库和实体框架,我现在正试图从我的数据库中取出所有数据,但我似乎无法在我的方法中使用ProjectTo<T>()方法我正在写。 It does not show up in my autocomplete on VS Studio and throws me the error它没有出现在我在 VS Studio 上的自动完成功能中,并向我抛出了错误

IIncludableQueryable<User, DateTime>' does not contain a definition for 'ProjectTo' and no accessible extension method 'ProjectTo' accepting a first argument of type 'IIncludableQueryable<User, DateTime>' could be found (are you missing a using directive or an assembly reference?) IIncludableQueryable<User, DateTime>' 不包含 'ProjectTo' 的定义,并且没有可访问的扩展方法 'ProjectTo' 接受类型为 'IIncludableQueryable<User, DateTime>' 的第一个参数(您是否缺少 using 指令或装配参考?)

So I was wondering if anyone knew how to fix this?所以我想知道是否有人知道如何解决这个问题? Thanks for your help in advance提前感谢您的帮助

Here is my code:这是我的代码:

UserRepository.cs:用户存储库.cs:

using GraphQL.Introspection;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AppName.GraphQL
{
    public class UserRepository
    {
        private readonly UserDBContext userDBContext;

        public UserRepository(UserDBContext userDBContext)
        {
            this.userDBContext = userDBContext;
        }

        //GET request to get all the users from the db
        public async Task<List<T>> GetAll<T>()
        {
            return await userDBContext
                .Users
                .Include(x => x.Id)
                .Include(x => x.Username)
                .Include(x => x.Password)
                .Include(x => x.Email)
                .Include(x => x.DateOfBirth)
                .Include(x => x.DateCreated)
                .ProjectTo<T>()//throws the error
                .ToListAsync();
        }

        public async Task<IEnumerable<User>> GetAll()
        {
            return await userDBContext
                .Users
                .Include(x => x.Id)
                .Include(x => x.Username)
                .Include(x => x.Password)
                .Include(x => x.Email)
                .Include(x => x.DateOfBirth)
                .Include(x => x.DateCreated)
                .ToListAsync();
        }
    }
}

UserContext.cs用户上下文.cs

namespace AppName.GraphQL
{
    public class UserDBContext : DbContext
    {
        public static string DbConnectionString = "mongodb://localhost:27020/PetPetOnline";
        
        public UserDBContext(DbContextOptions<UserDBContext> options) : base(options) { }

        public DbSet<User> Users { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>().HasData(new User(ObjectId.GenerateNewId(),"Jon", "abadpassword", "jon@PetPetOnline.xyz", DateTime.ParseExact("1998-01-16 00:00:00,000", "yyyy-MM-dd HH:mm:ss,fff", System.Globalization.CultureInfo.InvariantCulture), DateTime.Now));
            base.OnModelCreating(modelBuilder);
        }
    }
} 

and User.cs和 User.cs

public class User
{
    [Key]
    public  ObjectId Id { get; set; }

    [Required]
    [StringLength(100)]
    public string Username { get; set; }

    [Required]
    [StringLength(200)]
    public string Password { get; set; }

    [Required]
    [StringLength(200)]
    public string Email { get; set; }

    [Required]
    public DateTime DateOfBirth { get; set; }

    public DateTime DateCreated { get; set; }

    public User(ObjectId id, string username, string password, string email, DateTime dateOfBirth, DateTime dateCreated)
    {
        Id = id;
        Username = username;
        Password = password;
        Email = email;
        DateOfBirth = dateOfBirth;
        DateCreated = dateCreated;
    }
}

I wanted to give some recomendations before solution.我想在解决方案之前给出一些建议。

  1. You need to use the .Include() function only for navigation properties.您只需要将.Include() function 用于导航属性。
  2. I'm not sure if you really need a generic type for function GetAll<T> (anyway I will give you a solution to check if automapper support the projection).我不确定你是否真的需要 function GetAll<T>的泛型类型(无论如何我会给你一个解决方案来检查自动映射器是否支持投影)。 Maybe you want to change it to UserDto type?也许您想将其更改为UserDto类型?

To start you need to install AutoMapper.要开始,您需要安装 AutoMapper。 You're using Asp.Net Core, then I recommend you to install the AutoMapper.Extensions.Microsoft.DependencyInjection您使用的是 Asp.Net Core,那么我建议您安装AutoMapper.Extensions.Microsoft.DependencyInjection

Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection

Now you need to configure the AutoMapper.现在您需要配置 AutoMapper。 To make it simply, I will use the AutoMapAttribute but for complex mapping definitions I recommend you to use AutoMapper Profile.为了简单起见,我将使用AutoMapAttribute ,但对于复杂的映射定义,我建议您使用 AutoMapper Profile。

[AutoMap(typeof(User))]
public class UserDto
{
    public string Username { get; set; }
    public string Email { get; set; }
    //add the other properties if you need it
}

Then go to Startup class, and register the AutoMapper configuration.然后 go Startup class,并注册 AutoMapper 配置。

public void ConfigureServices(IServiceCollection services)
{
    services.AddAutoMapper(o => o.AddMaps(typeof(Startup).Assembly));
...

The UserRepository : UserRepository

public class UserRepository
{
    private readonly UserDbContext _userDbContext;
    private readonly IMapper _mapper;

    public UserRepository(UserDbContext userDbContext, IMapper mapper)
    {
        _userDbContext = userDbContext;
        _mapper = mapper;
    }
    
    public async Task<List<T>> GetAll<T>()
    {
        var supportProjection = _mapper.ConfigurationProvider
            .GetAllTypeMaps()
            .Any(x => x.SourceType == typeof(User) && x.DestinationType == typeof(T));

        if (!supportProjection)
            throw new InvalidOperationException("Unsupported projection type");

        return await _userDbContext
            .Users
            .ProjectTo<T>(_mapper.ConfigurationProvider)
            .ToListAsync();
    }
    
    public async Task<IEnumerable<User>> GetAll()
    {
        return await _userDbContext
            .Users
            .ToListAsync();
    }
}

You need to add AutoMapper to your project and then add using AutoMapper;您需要将 AutoMapper 添加到您的项目中,然后using AutoMapper; to the class in which you are using it.到您正在使用它的 class 。

Install AutoMapper from the package manager console or from Nuget Package Manager.从 package 管理器控制台或 Nuget Package 管理器安装 AutoMapper。

PM> Install-Package AutoMapper

Reference:参考:

https://docs.automapper.org/en/stable/Queryable-Extensions.html#queryable-extensions https://docs.automapper.org/en/stable/Queryable-Extensions.html#queryable-extensions

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在.NET Standard项目中找不到Microsoft.EntityFrameworkCore类型 - Type not found Microsoft.EntityFrameworkCore in .NET Standard project 如何为 Microsoft.EntityFrameworkCore 3.1 方法 FirstOrDefaultAsync 创建 xunit 测试? - How to create xunit test for Microsoft.EntityFrameworkCore 3.1 method FirstOrDefaultAsync? Microsoft.EntityFrameworkCore 中 ExecuteScalar 的对应项 - Counterpart of ExecuteScalar in Microsoft.EntityFrameworkCore 命名空间“Microsoft.EntityFrameworkCore”中不存在“迁移” - 'Migrations' does not exist in the namespace 'Microsoft.EntityFrameworkCore' 如何禁用 Microsoft.EntityFrameworkCore 中的约定? - How to disable conventions in Microsoft.EntityFrameworkCore? 网站无法加载 Microsoft.EntityFrameworkCore - Website cannot load Microsoft.EntityFrameworkCore 安装Microsoft.EntityFrameworkCore v1.1.4时出错 - Error Installing Microsoft.EntityFrameworkCore v1.1.4 无法从 Nuget 包管理器安装 Microsoft.EntityFrameworkCore - Not able to install Microsoft.EntityFrameworkCore from Nuget Package Manager 找不到方法:'无效 Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator..ctor(Microsoft.EntityFrameworkCore.Migrations.IMigrationsAssembly - Method not found: 'Void Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator..ctor(Microsoft.EntityFrameworkCore.Migrations.IMigrationsAssembly Microsoft.EntityFrameworkCore 未在 Web API .NET Core 应用程序中安装和挂起 - Visual Studio 2019 - Microsoft.EntityFrameworkCore not installing and hanging in Web API .NET Core app - Visual Studio 2019
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM