私はMVC 3を学習していますが、データモデルクラスのプロパティ内でロジックコードを使用している人が見つかりませんでした。 (例えば)以下のようにデータモデルクラスのプロパティ内にいくつかのロジックコードを持つことはできますか?
彼らは、データモデルクラスを実行します。次のように
public class Customer
{
public int CustomerId {get;set;}
//other properties without any logic code.
}
は、それがプロパティ内のロジック・コードを持ってしても大丈夫ですか?
public class Customer
{
private int customerId;
public int CustomerId {
get{return customerId;}
set
{
customerId=value;
// some logic codes go here.
}
}
//other properties go here.
}
編集1:
これは私の本当のシナリオです:
子テーブルデータモデル:
namespace MvcApplication1.Models
{
public class Choice
{
public int ChoiceId { get; set; }
public string Description { get; set; }
public bool IsCorrect { get; set; }
public QuizItem QuizItem { get; set; }
}
}
親テーブルデータモデル:
namespace MvcApplication1.Models
{
public class QuizItem
{
public int QuizItemId { get; set; }
public string Question { get; set; }
private IEnumerable<Choice> choices;
public IEnumerable<Choice> Choices
{
get { return choices; }
set
{
choices = value;
foreach (var x in choices)
x.QuizItem = this;
}
}
}
}
消費者:
namespace MvcApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
var data = new List<QuizItem>{
new QuizItem
{
QuizItemId = 1,
Question = "What color is your hair?",
Choices = new Choice[]{
new Choice{ ChoiceId=1, Description="Black.", IsCorrect=true},
new Choice{ ChoiceId=2, Description="Red.", IsCorrect=false},
new Choice{ ChoiceId=3, Description="Yellow.", IsCorrect=false}
}
},
new QuizItem
{
QuizItemId = 2,
Question = "What color is your noze?",
Choices = new Choice[]{
new Choice{ChoiceId=1, Description="Pink.", IsCorrect=false},
new Choice{ChoiceId=2, Description="Maroon.", IsCorrect=true},
new Choice{ChoiceId=3, Description="Navy Blue.", IsCorrect=false}
}
}
};
return View(data);
}
}
}
あなたのセッターでは何をしていますか? – alexn
IMO、プロパティ設定ツールに*合理的な副作用があるのは大丈夫です。例として、 'PropertyChanged'イベントを発生させることは許容されます、' new NuclearMissile()。Launch() 'はそうではありません。 – Ani
@alexn:実際のシナリオを表すために質問を更新します。 – xport