首页 > 解决方案 > 具有可为空属性的多个条件的 EF Core 联接表

问题描述

我有以下表结构:

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;}
    }

Delegate 和 TrainingNotification 之间的一对多

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

想要在 Delegate 中检索 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

谢谢

标签: c#linq-to-sqlentity-framework-core-2.1

解决方案


这可能是因为您没有明确识别匿名类型的各个部分。尝试:

 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 } 

推荐阅读