基础模型和MVC
问题描述:
我放在一起,我已经创建了一个基础模型,然后有四个派生出来的型号,所有这些都从基础模型继承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作为属性。
考虑到这一点:
- 是使用继承与模型以这种方式走的路?如果是这样,我如何获得特定于视图中派生模型的字段?
- 如果在这种情况下不推荐使用继承,那我应该用什么来取代它?
感谢
答
有原来是一个简单的答案。 EF的数据库中没有填充Transaction
属性之一。这意味着TransactionType
为空,导致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