0
我放在一起,我已經創建了一個基礎模型,然後有四個派生出來的型號,所有這些都從基礎模型繼承MVC應用程序中派生出來的型號:基礎模型和MVC
public abstract class BaseFund
{
public string Name { get; set; }
public int AccountId { get; set; }
public abstract decimal Value { get; }
public virtual InvestmentAccount Account { get; set; }
}
之一派生的模型:
public class ShareFund : BaseFund
{
public string ISIN { get; set; }
public ShareFundType FundType { get; set; }
public IncomeStatus IncomeStatus { get; set; }
public decimal TotalShares {
get
{
ICollection<ShareTransaction> tt = this.Transactions;
var outgoings = Transactions.Count > 0 ? Transactions.Where(t => t.TransactionType.IsOutgoing.Equals(true)).Sum(a => a.Units) : 0;
var incomings = Transactions.Count > 0 ? Transactions.Where(t => t.TransactionType.IsOutgoing.Equals(false)).Sum(a => a.Units) : 0;
return incomings - outgoings;
}
}
public override decimal Value
{
get
{
return this.TotalShares * (this.SharePrice/100);
}
}
public decimal SharePrice { get; set; }
public ICollection<ShareTransaction> Transactions { get; set; }
}
還有三個其他派生模型是相似的。所有的模型都是實體框架使用的POCO。
編輯:鑑於在這個階段標準的MVC腳手架的東西:
<table>
<tr>
<th>
Name
</th>
<th>
Account
</th>
<th>
Value
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Account.AccountNumber)
</td>
<td>
@Html.DisplayFor(modelItem => item.Value)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
我想要做的就是創建一個視圖,顯示從基地基金(姓名,帳戶ID和值)的字段。問題在於,對於每個派生模型而言,計算值的邏輯是不同的 - 對於ShareFund,它使用TotalShares,因此View中使用的BaseFund必須轉換爲ShareFund類型。其他派生模型不一定將TotalShares作爲屬性。
考慮到這一點:
- 是使用繼承與模型以這種方式走的路?如果是這樣,我如何獲得特定於視圖中派生模型的字段?
- 如果在這種情況下不推薦使用繼承,那我應該用什麼來取代它?
感謝
爲什麼'BaseFund'的部分視圖只能使用'this.Model.Value'?它會通過一個具體的類型(如'ShareFund'),所以不應該這樣工作?如何發佈您的視圖代碼的考慮? – 2011-06-08 10:02:35
您是說當類是'ShareFund'的一個實例但被引用爲基類('BaseFund')時調用'item.Value'不是調用返回'TotalShares'的內部實現嗎? – Lazarus 2011-06-08 10:02:40
@Steve Wilkes:已添加視圖代碼 – Col 2011-06-08 10:13:29