“LINQ to Entities无法识别方法'Boolean ***,并且此方法无法转换为商店表达式。”

时间:2015-02-03 07:54:18

标签: linq asp.net-mvc-5 linq-to-entities linq-expressions

我正在编写MVC 5互联网应用程序,并收到以下错误:

base = {"LINQ to Entities does not recognize the method 'Boolean IsAccountSetupForSendingFreeTrialSubscriptionExpirationEmail(CanFindLocation.Models.Account)' method, and this method cannot be translated into a store expression."}

以下是我的方法:

public IEnumerable<Account> GetFreeTrialAccountsForSendDailyExpirationEmails(int minimumDaysLeftInSubscriptionForEmail)
{
    IEnumerable<Account> freeTrialAccounts = genericMultipleRepository.accounts.Value.SearchFor(a => IsAccountSetupForSendingFreeTrialSubscriptionExpirationEmail(a) && ShouldDailyExpirationEmailBeSentForFreeTrialAccount(a, minimumDaysLeftInSubscriptionForEmail));
    return freeTrialAccounts;
}

public bool IsAccountSetupForSendingFreeTrialSubscriptionExpirationEmail(Account account)
{
    if (account.isFreeTrial && account.sendSubscriptionExpirationEmail)
    {
        return true;
    }
    else
    {
        return false;
    }
}

public bool ShouldDailyExpirationEmailBeSentForFreeTrialAccount(Account account, int minimumDaysLeftInSubscriptionForEmail)
{
    if (IsExpiresDateTimeLessThanMinimumDaysLeftInFreeTrialSubscription(account, minimumDaysLeftInSubscriptionForEmail) && !HasSubscriptionEmailBeenSentForCurrentFreeTrialEndDateTime(account))
    {
        return true;
    }
    else
    {
        return false;
    }
}

public bool IsExpiresDateTimeLessThanMinimumDaysLeftInFreeTrialSubscription(Account account, int minimumDaysLeftInSubscriptionForEmail)
{
    TimeSpan expires = account.freeTrialEndDate - DateTime.UtcNow;
    return expires.Days < minimumDaysLeftInSubscriptionForEmail;
}

public bool HasSubscriptionEmailBeenSentForCurrentFreeTrialEndDateTime(Account account)
{
    return account.subscriptionEndDateForExpirationEmail == account.freeTrialEndDate;
}

我的帐户对象包含以下字段:

public bool isFreeTrial { get; set; }
public bool sendSubscriptionExpirationEmail { get; set; }
public DateTime subscriptionEndDateForExpirationEmail { get; set; }
public DateTime freeTrialEndDate { get; set; }

我做了一些研究,并且我认为我编写的代码无法转换为LINQ表达式。

我需要做什么才能将我的代码转换为有效的表单,以便LINQ to Entities不会执行错误?

提前致谢。

1 个答案:

答案 0 :(得分:3)

您无法将LinqToXXX查询重构为方法。

例如。

IQueryable<Foo> foos = ...;
IQueryable<Foo> results = from f in foos
                          where f.IsBar
                          select f;

相比,结果与IL完全不同
IQueryable<Foo> foos = ...;
IQueryable<Foo> results = from f in foos
                          where FooIsBar(f)
                          select f;


public bool FooIsBar(Foo foo)
{
    return foo.IsBar;
}

后者会尝试将FooIsBar传递给EntityFramework以“转换”。由于此时EntityFramework无法访问源代码,因此无法将已编译的IL代码转换为SQL。

替代方案如下......

IQueryable<Foo> foos = ...;
IQueryable<Foo> results = from f in foos.Where(FooIsBar)
                          select f;


public Expression<Func<Foo, bool>> FooIsBar
{
    get { return foo => foo.IsBar; }
}