0
我有兩個實體是這樣的:去除的LINQ查詢連接
[Table("tblAccount")]
public class Account
{
[Key]
[Column("Creditor Registry ID", Order = 0)]
public int CreditRegistryId { get; set; }
[Key]
[Required]
[Column("Account No", Order = 1)]
public int AccountNo { get; set; }
[Column("Minimum Installment")]
public decimal MinimumInstallment { get; set; }
[Column("Account Status Date")]
public DateTime AccountStatusDate { get; set; }
[Required]
[Column("Account Type")]
public string AccountType { get; set; }
public virtual ICollection<AccountOwner> AccountOwners { get; set; }
}
和
[Table("tblAccountOwner")]
public class AccountOwner
{
[Key]
[ForeignKey("Account")]
[Column("Creditor Registry ID", Order = 0)]
public int CreditorRegistryId { get; set; }
[Key]
[ForeignKey("Account")]
[Column("Account No", Order = 1)]
public int AccountNo { get; set; }
[Key]
[Column("Account Owner Registry ID", Order = 2)]
public long AccountOwnerRegistryId { get; set; }
public virtual Account Account { get; set; }
}
我想轉換下面的查詢工作,而加入作爲帳戶實體有accountOwners和accounOwner有帳戶導航財產(主鍵/外鍵關係)
var ownerRegId = 731752693037116688L;
var excludeTypes = new[] { 'CA00', 'CA01', 'CA03', 'CA04', 'CA02', 'PA00', 'PA01', 'PA02', 'PA03', 'PA04' };
var maxStateChangeMonth = 4;
var excludeStatusId = 999;
var SumOfMonthlyPayments =
context.Accounts
.Join(context.AccountOwners,
a => new { CreditorRegistryId = a.CreditRegistryId, a.AccountNo },
ao => new { ao.CreditorRegistryId, ao.AccountNo },
(a, ao) => new { Account = a, AccountOwner = ao })
.Where(x => x.AccountOwner.AccountOwnerRegistryID == ownerRegId
&& !excludeTypes.Contains(x.Account.AccountType)
&& (x.Account.StateChangeDate == null || x.Account.StateChangeDate.Month - DateTime.Now.Month <= maxStateChangeMonth)
&& x.Account.AccountStatusID != excludeStatusId)
.Sum(x => Math.Abs(x.Account.MinimumInstallment));
由於Sergi建議我發起d這樣的:
var sum = (from account in context.Accounts
from owner in account.AccountOwners
where (owner.AccountOwnerRegistryId == ownerRegistryId
&& !excludeTypes.Contains(account.AccountType)
&& (account.StateChangeDate == null ||
(account.StateChangeDate.Month - DateTime.Now.Month)
<= maxStateChangeMonth)
&& account.AccountStatusId != excludeStatusId
&& (includeMortgage.Contains(account.AccountType) ||
account.AccountType.Contains("Mortgage")))
select account.MinimumInstallment)
.Sum(minimumInstallment => Math.Abs(minimumInstallment));
我加了一個其他& &條款
&& (includeMortgage.Contains(account.AccountType) ||
account.AccountType.Contains("Mortgage")
,但現在我得到:
The cast to value type 'Decimal' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
感謝
謝謝。我做了更改並添加了一個新的過濾器,但現在我得到了:由於物化值爲空,因此值類型'Decimal'的強制轉換失敗。結果類型的泛型參數或查詢都必須使用可爲空的類型。 請參閱更新後的問題 – DotnetSparrow 2011-04-03 10:47:20
@DotnetSparrow - 這可能意味着'select account.MinimumInstallment'行正在返回'null',即該查詢不返回任何結果,並且'Sum'通過'null' 。你可以嘗試運行不含'.Sum(...)'行的查詢嗎?你有什麼結果嗎?結果中是否有「空」結果? – 2011-04-03 11:11:56