C# 如何首先在实体框架代码中将对象添加到对象列表中

C# 如何首先在实体框架代码中将对象添加到对象列表中,c#,asp.net-mvc,entity-framework,C#,Asp.net Mvc,Entity Framework,我正在使用实体框架代码。首先,我有两个对象项目和调查问卷。项目对象有一个调查问卷列表,其中一个是多个关联 这是我的代码: 项目类: public class Projet { [Key] public int codeProjet { get; set; } [Required(ErrorMessage="Veuillez entrer la designation du projet")] [MaxLength(250)] [Display(Name

我正在使用实体框架代码。首先,我有两个对象项目调查问卷。项目对象有一个调查问卷列表,其中一个是多个关联
这是我的代码:

项目类

public class Projet
{
    [Key]
    public int codeProjet { get; set; }

    [Required(ErrorMessage="Veuillez entrer la designation du projet")]
    [MaxLength(250)]
    [Display(Name = "Designation")]
    public String designation{ get; set; }

    [Display(Name="Date début")]
    public DateTime dateDebut { get; set; }

    [Display(Name="Date fin ")]
    public DateTime dateFin { get; set; }

    [Column("desciption", TypeName = "ntext")]
    [Display(Name="Desciption du projet ")]
    public String desciption { get; set; }

    [MaxLength(100)]
    [Display(Name="Responsable du projet")]
    public String responsable { get; set; }

    [Display(Name = "Budget du projet")]
    public double budget { get; set; }

    public virtual ICollection<Questionnaire> questionnaires { get; set; }
}
public class Questionnaire
{
    [Key]
    public int codeQuestionnaire { get; set; }

    [MaxLength(250)]
    [Display(Name="Desciption du questionnaire")]
    public String designation { get; set; }

    [Display(Name = "Questionnaire avec GPS ?")]
    public bool avecGPS { get; set; }
    public bool avecNote { get; set; }

    //foreign key Projet entity 
    //[Required]
    public int projetId { get; set; }
    [ForeignKey("projetId")]
    public virtual Projet projet { get; set; }           
}
上下文类:

public class QuestContext :DbContext
{
    public QuestContext() : base("name=QuestionnaireDbContext") { }

    public DbSet<Projet> projets { get; set; }
    public DbSet<Questionnaire> questionnaires { get; set; }     
}

我的问题是如何将问卷对象添加到现有的Projet对象?谢谢

您只需将问卷添加到项目的问卷收集中即可。如果projet和问卷之间的关系定义正确,将自动生成正确的外键

var existingProject = QuestContext.projets.Find(projetId);
var newQuestionnaire = new Questionnaire();
existingProject.questionnaires.Add(newQuestionnaire);
QuestContext.SaveChanges();

您只需将调查问卷添加到项目的调查问卷集合中即可。如果projet和问卷之间的关系定义正确,将自动生成正确的外键

var existingProject = QuestContext.projets.Find(projetId);
var newQuestionnaire = new Questionnaire();
existingProject.questionnaires.Add(newQuestionnaire);
QuestContext.SaveChanges();

您是否尝试过使用?是保存我使用的projet对象(var ctx=new QuestContext){ctx.projets.add(projet);ctx.SaveChanges();}我想通过向项目添加新的问卷对象来更新projet您尝试过使用吗?是保存我使用的projet对象(var ctx=new QuestContext){ctx.projets.add(projet);ctx.SaveChanges();}我想通过向projet添加新的问卷对象来更新projet