【问题标题】:How to include a navigation property without selecting a new Model?如何在不选择新模型的情况下包含导航属性?
【发布时间】:2019-06-27 14:27:47
【问题描述】:

嗯,我基本上是在尝试这个:

_dbContext.BarcodeEvents.Include(e => e.BarcodeType).ToList();

现在我期待我得到一个 BarcodeEvents 列表,其中设置了导航属性 BarcodeType。问题是,BarcodeTypenull。然后我配置 EF Core 来输出生成的查询,结果发现,它简单地忽略了连接。

首先我认为,我的导航属性配置有一些错误,但后来我意识到,将其具体化为新模型时它正在工作:

_dbContext.BarcodeEvents.Include(e => e.BarcodeType).Select(e => new
{
    e.EventTimestamp, //root property also available
    e.BarcodeType.BarcodeTypeDescription // navigation property available in this case
    //...
}).ToList();

是否可以在不创建新模型的情况下选择整个BarcodeEvents,包括BarcodeType

我试过了,但是导航属性还是null

_dbContext.BarcodeEvents.Include(e => e.BarcodeType).Select(e => e).ToList();

仅供参考,这里是我的实体:

public class BarcodeEvents
{
    [Column("EventID")]
    public Guid EventId { get; set; }

    [Column(TypeName = "datetime")]
    public DateTime EventTimestamp { get; set; }

    [Column("DeviceID")]
    public int DeviceId { get; set; }

    public byte DataType { get; set; }

    [ForeignKey(nameof(DataType))]
    public virtual BarcodeTypes BarcodeType { get; set; }

    public string RawData { get; set; }
    public string DataLabel { get; set; }
    public string DecodedBarcode { get; set; }
}

public class BarcodeTypes
{
    [Key]
    [Column("BarcodeTypeID")]
    public byte BarcodeTypeId { get; set; }

    [StringLength(50)]
    public string BarcodeTypeDescription { get; set; }
}

【问题讨论】:

    标签: c# entity-framework entity-framework-core navigation-properties


    【解决方案1】:

    问题是,我有一个包含 2 个框架版本(实体框架 6 和实体框架核心)的项目。

    我使用的Include 方法来自:

    using System.Data.Entity
    

    而不是正确的

    using Microsoft.EntityFrameworkCore
    

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 2013-03-30
      • 2023-04-09
      • 2020-08-31
      • 1970-01-01
      • 1970-01-01
      • 2020-06-07
      相关资源
      最近更新 更多