简体   繁体   中英

How to insert data to nested table in asp.net core

Suppose that I have 3 different tables, Form -> Topic -> Question which has navigation property.
These tables will look like

Form : FormId, (List)Topic | Topic : TopicId, (List)Question | Question: QuestionId, Content

I want to insert data to Question table, but I need to specify an Id for FormId and TopicId to identify which Form and Topic I'll insert to.

I have tried this code

var ref = _context.Form.Include(t=>t.Topic).ThenInclude(q=>q.Question).Add(Data);

but It could not find reference to Question table so I can't insert data to table.
anyone knows how to insert data to nested table like this?

Already you know this "Question" is adding to which "Topic". You should find it and add your "Question" to it and update and save context. In this case, you should add "TopicId" to "Question".

Please look at my example:

public class Form
{
    [Key]
    public int Id { get; set; }
    public List<Topic> Topics { get; set; }
}

public class Topic
{
    [Key]
    public int Id { get; set; }
    public List<Question> Questions { get; set; }

    public int FormId { get; set; }
    [ForeignKey("FormId")]
    public Form Form { get; set; }
}

public class Question
{
    [Key]
    public int Id { get; set; }
    public string Content { get; set; }

    public int TopicId { get; set; }
    [ForeignKey("TopicId")]
    public Topic Topic { get; set; }
}

After migration it like this:

在此输入图像描述

Now, let me add a "Question in this structure:

Question question = new Question() { Content = "Some content", TopicId = 1 };
Topic topic = dbContext.Topics.SingleOrDefault(x => x.Id == question.TopicId);
if(topic != null)
{
    topic.Questions.Add(question);
    dbContext.SaveChanges();
}

I hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM