为此关系配置一个主键或一组兼容的外键属性

时间:2019-03-05 15:07:45

标签: c# asp.net-core entity-framework-core odata

尝试使用Entity Framework Core和OData制作Rest API。 我有2个模型。一个叫InvoiceModel,另一个叫InvoiceLinesModel

InvoiceModel基本上是有关发票的基本信息,然后具有包含项目(增值税,折扣等)的行(InvoiceLines)

在这里看到两个模型:

InvoiceModel

public class InvoiceModel
{
    [ForeignKey("Id")]
    public Guid Id { get; set; }
    [ForeignKey("Number")]
    public string Number { get; set; }
    [ForeignKey("Customer")]
    public Guid Customer { get; set; }
    public decimal SubTotal { get; set; }
    public decimal VatTotal { get; set; }
    public decimal Total { get; set; }
    public DateTime Created { get; set; }
    public DateTime Date { get; set; }
    public bool IsOpen { get; set; }
    public string YourReference { get; set; }
    [ForeignKey(nameof(InvoiceLinesModel.Number))]
    public ICollection<InvoiceLinesModel> Lines { get; set; }
}

InvoiceLinesModel

public class InvoiceLinesModel
{
    [ForeignKey("Id")]
    public Guid Id { get; set; }
    [ForeignKey("LineNumber")]
    public int LineNumber { get; set; }

    public Guid Customer { get; set; }

    [ForeignKey("Number")]
    public string Number { get; set; }
    public string ItemCode { get; set; }
    public string ItemDescription { get; set; }
    public decimal PriceExcl { get; set; }
    public decimal PriceIncl { get; set; }
    public decimal DefaultPrice { get; set; }
    public decimal VatPercentage { get; set; }
    public decimal Quantity { get; set; }
    public decimal Discount { get; set; }
    public decimal TotalDiscount { get; set; }
    public string Instruction { get; set; }
    //public InvoiceModel Invoice { get; set; }
}

现在,在控制器内部,我尝试从2个proc中获取数据。 然后,使用foreach,我要将InvoiceLines添加到Invoice对象的集合中。

 public IQueryable<InvoiceModel> GetInvoices()
        {
            IQueryable<InvoiceModel> Invoices = null;
            ICollection<InvoiceLinesModel> InvoiceLines = null;

            Invoices = db.Invoices.FromSql("SIP_API_MONDIA_InvoiceMain_sel");
            InvoiceLines = db.InvoiceLines.FromSql("SIP_API_MONDIA_InvoiceDetail_sel").ToList();
            foreach (var item in Invoices)
            {
                item.Lines = InvoiceLines.Where(m => m.Number == item.Number).ToList();
            }
            return Invoices;

问题是由于将actionResult结果更改为IQueryAble,所以在此行出现错误,因为我需要能够使用$ expand OData功能以OData返回Collections,对吗?

    Invoices = db.Invoices.FromSql("SIP_API_MONDIA_InvoiceMain_sel");

错误:

  

System.InvalidOperationException:'来自   带外键的'InvoiceLinesModel'到'InvoiceModel.Lines'   属性{'Number':string}无法定位主键{'Id':   Guid},因为它不兼容。配置主键或集合   关系的兼容外键属性。”

编辑:在我们的例子中,数字(是一个字符串。不要问我为什么命名不相同)是比较/链接的关键。

如您在控制器中所见:

  foreach (var item in Invoices)
            {
                item.Lines = InvoiceLines.Where(m => m.Number == item.Number).ToList();
            }

0 个答案:

没有答案