具有可空属性的多个条件的EF Core连接表

时间:2019-12-20 13:18:39

标签: c# linq-to-sql entity-framework-core-2.1

我具有以下表结构:

public class Delegate {
    public int DelegateId {get;set;}
    public int? NotificationTypeId { get; set; }
    public NotificationType NotificationType { get; set; }
}

    public class TrainingNotification {
        public int TrainingNotificationId {get;set;}
public int NotificationTypeId {get;set;}
        public int DelegateId {get;set;}
        public virtual Delegate Delegate {get;set;}
    }

委托与培训通知之间一对多

public class NotificationType {
    public int NotificationTypeId {get;set;}
    public virtual ICollection<Delegate> Delegates {get;set;}
}

要检索代表中NotificationTypeId的TrainingNotification。

    var delegates21 = await from tn in _context.TrainingNotification
                            join cd in _context.Delegate on
                            new { tn.DelegateId, tn.NotificationTypeId } equals
                            new { cd.DelegateId, cd.NotificationTypeId } 

但出现错误 连接子句中表达式之一的类型不正确

任何人都可以帮助解决此问题吗?

以下是测试数据和预期结果:

Delegate:
DelegateId  NotificationTypeId
100             1
8201            2
101             null


TrainginNotification:
TrainignNotificationId  DelegateId  NotificationTypeId
1                           8201        1
2                           8201        2
3                           100         1


NotificationType:
NotificationTypeId      Name
1                       InviteEmail
2                       ReminderEmail

Retrieve users who hasnt got reminder emails:

Result:

DelegateId      
100

谢谢

2 个答案:

答案 0 :(得分:0)

这可能是因为您尚未明确标识匿名类型的各个部分。试试:

 var delegates21 = await from tn in _context.TrainingNotification
                        join cd in _context.Delegate on
                        new { did = tn.DelegateId, nid = tn.NotificationTypeId } equals
                        new { did = cd.DelegateId, nid = cd.NotificationTypeId } 

答案 1 :(得分:0)

由于NotificationTypeIdDelegate类型上可为空,但在TrainingNotifcation类型上不可为空,因此可以将TrainingNotification.NotificationTypeId强制转换为int?

var delegates21 = await from tn in _context.TrainingNotification
                            join cd in _context.Delegate on
                            new { tn.DelegateId, (int?)tn.NotificationTypeId } equals
                            new { cd.DelegateId, cd.NotificationTypeId }

那应该很好。