Ich habe folgende Modell (vereinfacht):C# Instanziieren abgeleitete Klasse von Basiskonstruktor basierend auf Parametertyp
Datenbankmodelle:
public abstract class Question
{
public int Id { get; set; }
public string Text { get; set; }
}
public class QuestionA : Question
{
public bool OptionA { get; set; }
}
public class QuestionB : Question
{
public int OptionB { get; set; }
}
Ansicht Modelle:
public abstract class QuestionModel
{
public string Text { get; set; }
protected QuestionModel(Question question)
{
Text = question.Text;
}
}
public class QuestionAModel : QuestionModel
{
public bool OptionA { get; set; }
public QuestionAModel(QuestionA questionA) : base(questionA)
{
OptionA = questionA.OptionA;
}
}
public class QuestionBModel : QuestionModel
{
public int OptionB { get; set; }
public QuestionBModel(QuestionB questionB) : base(questionB)
{
OptionB = questionB.OptionB;
}
}
Grundsätzlich ist zu Zuordnen von Datenbankeinheiten zum Anzeigen von Modellen, und ich habe beispielsweise diesen Controller:
public class SomeController : Controller
{
public JsonResult Get()
{
// Simulating questions from the database
var questions = new List<Question>
{
new QuestionA { Id = 1, OptionA = true, Text = "fooA" },
new QuestionB { Id = 1, OptionB = 1, Text = "fooB" }
};
var model = questions.Select(q => new QuestionModel(q)).ToList();
return Json(model);
}
}
Diese obiously kompilieren nicht, weil die new QuestionModel(q)
ich die Art von jeder Frage aus der Datenbank wissen, wie ich abgeleitete Frage Modelle der jede Frage Einheit schaffen kann?
Danke an alle !!
Schön, ich wi Versuche das jetzt! –