在具有日期比较的 ICollection 上使用 Linq

Using Linq on an ICollection with Date Comparison

我正在使用标准的 ApplicationUser,并且我已经使用 public 虚拟 IColliction 配置文件增强了模型;

例如

public class ApplicationUser(){
    ...
    public virtual ICollection<Profile> profiles;
}

我的资料模特:

public class Profile(){
    public Guid ID;
    ...
    public System.DateTime ValidFrom;
    public System.DateTime ValidTo;    
}

我希望将配置文件的有效截止日期设置为 31/12/9999 的永不结束日期。我想在配置文件控制器中获取配置文件。

我尝试了以下方法:

System.DateTime EndDate = DateTime.Parse("31/12/9999");

            string currentUserId = User.Identity.GetUserId();
            ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);
            Profile profile = currentUser.Profiles.Select(s => s.ValidityEndDate >= EndDate);

我收到以下错误:

Error 1 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'datex.Models.Profile'. An explicit conversion exists (are you missing a cast?)

我假设我绝对不是正确的轨道,有人可以帮忙吗?

Select returns 一个 IEnumerable,而不是单个 Profile 对象。您应该使用 FirstOrDefault,例如 .FirstOrDefault(s => s.ValidityEndDate >= EndDate) 或更改 profile 变量的类型以接受 IEnumerable<Profile>.

日期与此错误无关,尽管在 DateTime.Parse 中使用特定于区域设置的字符串可能会导致在路上发布。在这种特殊情况下,您可以使用 DateTime.MaxValue 而不是硬编码日期