【问题标题】:Get all columns except one in EFCore获取 EFCore 中除一列之外的所有列
【发布时间】:2023-03-22 05:08:01
【问题描述】:

我的数据库中有一个用户表,其中包括用户名、加密密码、电子邮件和角色 ID。我想拉回除密码之外的所有用户的列表。

通过搜索,我找到了 ef 6 及以下版本的答案,但在 ef core 中没有任何问题。

这是我目前拥有的:

using (var context = new dbcontext())
{
     return context.Users.ToList()
}

我试过了

using (var context = new dbcontext())
{
     return context.Users
     .Select (u => new
     {
           Id = u.Id
           Username = u.Username
           Email = u.Email
      }
     .ToList()
}

这样做不会有任何回报。

我尝试将新实体和类映射到表中,省略了密码列,但没有返回任何内容。我想可能是因为它是必填字段。

目前我只是将响应转换为没有密码属性的新 UserSummary 类,但我认为有一种方法可以做到这一点,而无需返回密码。

【问题讨论】:

  • 你确定表有行吗?您还可以在 ef core 中为您的实体排除特定列
  • 是的,我很肯定这张桌子确实有。使用给出的第一个代码,我得到一个返回所有列的响应。如果可以排除列,请回答如何。我在这方面还没有成功。
  • 你用什么?数据注释还是 fluent api ?
  • 流利的API。我现在不能,但在早上我会用实体的映射方式编辑我的问题
  • 覆盖 DbContext 实例上的 OnModelCreating 方法并添加如下代码:modelBuilder.Entity() .Ignore(p => p.Password);

标签: .net-core entity-framework-core


【解决方案1】:

您可以使用您想使用的属性创建一个类,例如:

起源类:

public class Rating
{
    public Rating() { }
    public int IdRating { get; private set; }
    public string IdUser { get; set; }
    public decimal Value { get; private set; }
    public string Comment { get; private set; }
    public bool IsEnabled { get; set; }
    public int IdCorrespondent { get; private set; }}

目的地类:

public class RatingView
{
    public Rating() { }
    public int IdRating { get; private set; }
    public decimal Value { get; private set; }
}

并使用 select ex 方法将其映射到存储库:

public List<RatingView> ListRatings()
    {
        return _context.Ratings.Select(x => new RatingView
        {
            IdRating = x.IdRating ,
            Value = x.Value ,
        }).ToList();

    }

如果你不想改造课程,你可以使用 dapper 进行自己的查询,你可以找到关于 dapper 方式的有趣的事情here

【讨论】:

    猜你喜欢
    • 2021-01-11
    • 2019-09-27
    • 2020-12-03
    • 2011-01-26
    • 2018-08-29
    • 2012-10-03
    • 2013-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多