【问题标题】:Property for contacting fields in query LINQ to Entities查询 LINQ to Entities 中联系字段的属性
【发布时间】:2020-06-18 18:29:40
【问题描述】:

我在数据库表用户中有:

pk firstName lastName
1  Mary      Snow
...

LINQ to Entities 创建类:

public partial class User
{
   public int pk { get; set; }
   public string firstName { get; set; }
   public string lastName { get; set; }
}

我试图创建这个类的新部分

public partial class User
{
   public string FullName 
   {
      get
      {
        return lastName + " " + firstName;
      }
   }
}

在我尝试在 IQueryable 中使用它之后,我得到异常“LINQ to Entities 不支持指定的类型成员 'FullName'”。我可以为此创建属性或扩展方法吗?

我的代码的许多部分都需要它。在每个查询 lastName + " " + firstName 中使用它对我来说并不方便。我不明白为什么我可以在 IQueryable 中使用 "where(x=> (x.lastName + " " + x.firstName) == "Mary Show")" 但我不能编写新属性并将其用作 " where(x=> x.FullName == "玛丽秀")"。

这是我对字段进行更多修改的例子。

更新:我使用 .NET Framework 4.5.2 和 Entity Framework 6。

upd2:我使用数据库优先方法。

【问题讨论】:

  • 用 [NotMapped] 装饰属性
  • 我试过了。我使用 System.ComponentModel.DataAnnotations.Schema 添加;然后我添加 [NotMapped] 属性。它没有帮助,我使用它时遇到异常。
  • 抱歉,要先检查一下您使用的是 ef core 吗?
  • 没有。感谢您的评论,我添加了有关它的信息。
  • 您介意详细说明一下您是如何使用该物业的吗?请注意,我以为您只是在阅读实体。您无法访问 IQueryable 中的 fullName 等属性

标签: c# entity-framework entity-framework-6 linq-to-entities


【解决方案1】:

您也可以使用 Fluent API 覆盖 DBContext 类中的 OnModelCreating 函数来执行此操作:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Entity<User>().Ignore(t => t.FullName );
   base.OnModelCreating(modelBuilder);
}

【讨论】:

  • 哦,对不起。我使用数据库优先的方法,我忘记写了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多