【问题标题】:How to Include only parent table using Entity Framework?如何使用实体框架仅包含父表?
【发布时间】:2017-12-18 14:45:32
【问题描述】:

我正在通过 web api 返回数据。

FMSEntities db = new FMSEntities();
db.Voucher_BankReceipt.Include(x => x.Status)

status 是父表,它引用下面哈希集中给出的其他子表..

public Status()
{
        this.Voucher_BankPayment = new HashSet<Voucher_BankPayment>();
        this.Voucher_BankReceipt = new HashSet<Voucher_BankReceipt>();
        this.Voucher_CashPayment = new HashSet<Voucher_CashPayment>();
        this.Voucher_CashReceipt = new HashSet<Voucher_CashReceipt>();
        this.Voucher_Journal = new HashSet<Voucher_Journal>();
        this.Voucher_Log = new HashSet<Voucher_Log>();
        this.Voucher_Workflow = new HashSet<Voucher_Workflow>();
}

在包含父表状态时,它包含所有引用的哈希集对象。如何避免重新加载 Voucher_BankReceipt 和其他 hashset json?

【问题讨论】:

  • 像往常一样:关闭延迟加载。但答案中的选项更可取。
  • 我的回答满足你的问题了吗?如果是,请考虑接受。

标签: json entity-framework asp.net-web-api


【解决方案1】:

一般规则是永远不要将实体框架对象发送到 Web API JSON 序列化器中,而您刚刚发现了原因。

相反,您需要准确地从 EF 获取您需要的内容,或者您​​的 API 调用者需要的内容。序列化程序无法为您知道这一点。由于其性质,它几乎总是会抓取太多,甚至可能导致循环错误。

解决方案是创建对象/视图模型,复制调用者需要的 EF 对象部分,从 EF 对象中填充这些部分,然后返回它们。

一种快速而简单的方法是使用匿名对象,例如:

// Instead of "return EF_Product;" you can use this:
return new
{
    Product = new
    {
        Id = EF_Product.Id,
        Name = EF_Product.Name
    }
};

一个好的经验法则是仅将 EF 对象中的简单属性(数字、布尔值、字符串、日期时间)分配给 ViewModel 项。一旦遇到另一个 EF 对象(或 EF 对象集合)的 EF 对象属性,您就需要将它们转换为未链接到 EF 的“简单”对象。

另一方面,还有 AutoMapper 等库。如果您决定需要实际的 ViewModel 类,那么 AutoMapper 将帮助您以非常结构化的方式将 EF 对象映射到这些 ViewModel。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多