【问题标题】:Entity Framework .Include creating an incorrect JOIN?实体框架。包括创建不正确的 JOIN?
【发布时间】:2016-05-05 13:54:55
【问题描述】:

这是我第一次尝试将 EF 与 .include 一起使用,以便 JOIN 两个表。当我运行它时,我得到并错误“CallStatus_Id”是一个无效的列。没错,我的表中没有该字段,但我不知道 EF 为什么在其 SQL 查询中使用该字段。

我所做的是在我的 CustomerCall 表上创建一个外键,将 CustomerCall.Status 设置为 CallStatus.Id。我的想法是我将 PK 值存储在 CustomerCall.Status 字段中并将其加入 CallStutus.Id 以便我可以获得 CallStatus.StatusName 以进行显示。

这是我的 lambda 表达式:

var call = db.CustomerCalls.Include(s => s.CallStatus).Where(c => c.Id == id).FirstOrDefault();

我对 lambda 的理解是它调用 CustomerCalls 表,使用创建的 FK 将其加入 CallStatus 表,并且 WHERE 语句将根据传递到存储库的 id 提取 CustomerCall 的 Id方法。

它创建以下 SQL。您可以在 JOIN 中看到它创建的 [Extent1].[CallStatus_Id] 不正确。我没有那个栏目,应该是[Extent1].[Status],我不知道如何更正

这些是我的 EF 实体类:

namespace CPPCustomerCall.Models
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;

    [Table("CustomerCall")]
    public partial class CustomerCall
    {
        public int Id { get; set; }

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

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

        [Column(TypeName = "text")]
        public string Comment { get; set; }

        public DateTime? CallDate { get; set; }

        public int? Status { get; set; }

        public int? AssignedTo { get; set; }

        public DateTime? CreateDate { get; set; }


        public CallStatus CallStatus { get; set; }

    }
}

namespace CPPCustomerCall.Models
{
    using System.ComponentModel.DataAnnotations;

    public partial class CallStatus
    {
        public int Id { get; set; }

        [StringLength(25)]
        public string StatusName { get; set; }
    }
}

【问题讨论】:

  • 您是手动创建外键还是先通过 EF 代码创建外键?
  • 我是在 SQL Server 中完成的。我应该在 EF 中使用它吗?
  • 您需要在代码中以某种方式指定它,因为默认情况下 EF 不知道您已经创建了 FK。

标签: c# entity-framework lambda


【解决方案1】:

根据此处发布的建议,我似乎通过将 [ForeignKey("Status")] 注释添加到 CustomerCall 实体中的 CallStatus 导航属性来使其工作。我还需要在我的 CallStatus 实体的 Id 字段上设置 [Key]。

public partial class CustomerCall
    {
        public int Id { get; set; }

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

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

        [Column(TypeName = "text")]
        public string Comment { get; set; }

        public DateTime? CallDate { get; set; }

        public int? Status { get; set; }

        public int? AssignedTo { get; set; }

        public DateTime? CreateDate { get; set; }

        [ForeignKey("Status")]
        public CallStatus CallStatus { get; set; }

    }

public partial class CallStatus
    {
        [Key]
        public int Id { get; set; }

        [StringLength(25)]
        public string StatusName { get; set; }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多