【问题标题】:Can i have a property in my class that not exist in bd table using Entity Framework?我可以在使用实体框架的 db 表中拥有我的类中不存在的属性吗?
【发布时间】:2020-02-22 00:39:04
【问题描述】:

我的数据库中有一张表,如下所示:

Table_A
Col1 nvarchar(100)
Col2 nvarchar(100)
Col3 nvarchar(100)

现在在我的实体中:

public class Table_A
{
    public string Col1 {get; set;}
    public string Col2 {get; set;}
    public string Col3 {get; set;}
    public string Col4 {get; set;}
}

使用 EF,在某些情况下,我需要执行返回 Col1、Col2、Col3 和 Col4 的存储过程(Col4 是与其他表的左外连接中的列检索);问题是当我不使用那个 SP 时,我在 Col4 上得到一个错误。

我正在使用 EF Core 2.2.3 和 MS SQL Server 2017。

【问题讨论】:

  • 您是否尝试过添加NotMapped 属性?
  • 是的,不幸的是,当我使用返回 Col4 的 SP 时,属性中的值为 null。

标签: entity-framework


【解决方案1】:

我可以使用实体框架在我的类中拥有一个在 bd 表中不存在的属性吗?

是的,您可以使用NotMapped attribute

摘录:

public class Contact
{
    public int ContactId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    [NotMapped]
    public string FullName => $"{FirstName} {LastName}";
    public string Email { get; set; } 
}

或者您可以使用 Fluent API Ignore method

摘录:

public class SampleContext : DbContext
{
    public DbSet<Contact> Contacts { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Contact>().Ignore(c => c.FullName);
    }
}
public class Contact
{
    public int ContactId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName => $"{FirstName} {LastName}";
    public string Email { get; set; } 
}

使用 EF,在某些情况下,我需要执行返回 Col1、Col2、Col3 和 Col4 的存储过程(Col4 是与其他表的左外连接中的列检索);问题是,当我不使用该 SP 时,我在 Col4 上遇到错误。我正在使用 EF Core 2.2.3 和 MS SQL Server 2017。谢谢。

但这引出了一个问题,您的实际问题是:我可以有一个可选属性吗?答案是。财产要么;总是必须映射或从不映射。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多