EF6 - 选择与子表数据不匹配

时间:2015-06-25 07:45:15

标签: c# entity-framework

这是我的课程:

1

public partial class SmsScheduleType
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

2

public partial class SmsSchedule
{
    public int Id { get; set; }
    public int SiteId { get; set; }
    [ForeignKey("SiteId")]
    public virtual Site Site { get; set; }

    public int ScheduleTypeId { get; set; }
    [ForeignKey("Id")]
    public virtual SmsScheduleType SmsScheduleType { get; set; }

    public int DateToSend { get; set; }
    public int DayOfWeekToSend { get; set; }
    public string TimeToSend { get; set; }
    public string TextToSend { get; set; }
    public int Interval { get; set; }
}

这是一个SmsScheduleType数据

**Id  Name**
1; "Running"
3; "Weekly"
4; "Monthly"
5; "Daily"
2; "Idle"

这是

**Id SiteId DayOfWeekToSend TextToSend ScheduleTypeId DateToSend TimeToSend Interval Active**
2;     1;              0;  "Daily test";         5;          0;    "1500";    0;     t
4;     3;              0;  "Daily test";         1;          0;        "";   60;     f
5;     4;              0;     "Monthly";         4;          8;   "11:00";    0;     t

查询

var ready2send = context.SmsSchedules.ToList();
    foreach (var sch in ready2send)
    {                        
        Console.WriteLine("{0} is scheduled as {1}-{2}, {3}.", sch.Site.SiteID, sch.ScheduleTypeId ,sch.SmsScheduleType.Name, sch.SmsScheduleType.Id);
    }

查询结果

BHE152 is scheduled as 5-Idle, 2.
BHE155 is scheduled as 1-Monthly, 4.
BHE156 is scheduled as 4-Daily, 5.

我无法理解什么是错的。为什么Ids不匹配? 请帮忙 如果有意义,DB就是postgres。

1 个答案:

答案 0 :(得分:1)

应该是:

public partial class SmsSchedule
{
    public int Id { get; set; }
    public int SiteId { get; set; }
    [ForeignKey("SiteId")]
    public virtual Site Site { get; set; }

    public int ScheduleTypeId { get; set; }
    [ForeignKey("ScheduleTypeId ")]
    public virtual SmsScheduleType SmsScheduleType { get; set; }

    public int DateToSend { get; set; }
    public int DayOfWeekToSend { get; set; }
    public string TimeToSend { get; set; }
    public string TextToSend { get; set; }
    public int Interval { get; set; }
}

请注意,我已更改

[ForeignKey("Id")]

[ForeignKey("ScheduleTypeId ")]

当您使用[ForeignKey("Id")]时,告诉EF您将SmsScheduleType表的外键存储在 SmsSchedule 表的<{1}}字段中