C
C#2y ago
BokoGanga

Setting the id of an object to property in a nested Object on creation

Hey devs, I have a little tricky one this time, which is possibly very simple to implement. so I have an object, let's say Question implemented like this:
class Question{
int Id;
int Order;
List<QuestionText> QuestionTexts;
}
class Question{
int Id;
int Order;
List<QuestionText> QuestionTexts;
}
and the object QuestionText has the following implementation:
class QuestionText{
string Text;
int QuestionId;
string LocaleCode;
}
class QuestionText{
string Text;
int QuestionId;
string LocaleCode;
}
What i'm trying to achieve here is to create new instances of already made ones, in other terms, clone the objects and persist them in the db. here is an example of the code i'm trying to implement:
var newQuestions = questions.Select(q => new Question()
{
Order = q.Order,
QuestionTexts = q.QuestionTexts.Select(qt => new QuestionText()
{
Text = qt.Text,
LocaleCode = qt.LocaleCode,
QuestionId = "this needs to be the id of the new instance"
})
});
var newQuestions = questions.Select(q => new Question()
{
Order = q.Order,
QuestionTexts = q.QuestionTexts.Select(qt => new QuestionText()
{
Text = qt.Text,
LocaleCode = qt.LocaleCode,
QuestionId = "this needs to be the id of the new instance"
})
});
Is there anything i'm doing wrong here or am I missing something?
2 Replies
Becquerel
Becquerel2y ago
do you mean you want the questionid of the new questiontext to be that of the newly-created question? i'm assuming you have your db set up to auto create a new id when you insert the relevant row? if you are using entity framework it will deal with the foreign keys for you - no need to set ids manually otherwise, create a new id manually and set it to the new question
BokoGanga
BokoGanga2y ago
Yes, I meant the QuestionId of the new QuestionText needs to be that of the newly created question. I am using EF but I didn't know it would assign the foreign key value automatically on creation. I will try that and see the results. Thanks for your answer