如何添加多对多关系通过实体框架6,在代码

本文关键字:实体 框架 代码 关系 何添加 添加 | 更新日期: 2023-09-27 18:11:53

你好,我有以下类/模型映射到数据库使用Code-First

public class Speaker
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string Mobile { get; set; }
    public virtual ICollection<SpeakerCertification> Certifications { get; set; }
}
public class Certification
{
    public int Id { get; set; }
    public string Description { get; set; }
    public virtual ICollection<SpeakerCertification> Speakers { get; set; }
}
public class SpeakerCertification
{
    public int Id { get; set; }
    public int SpeakerId { get; set; }
    public int CertificationId { get; set; }
    public virtual Speaker Speaker { get; set; }
    public virtual Certification Certifications { get; set; }
}

已经用一些数据填充了认证表。在添加讲话者信息时,也必须添加讲话者认证(可以通过复选框选择)。现在我必须将这些信息添加到数据库中。我写了下面的代码和卡住(_ctx是dbContext)。我需要speakerCertification表的speakerId,但演讲者尚未添加到数据库中。要求是speakerId必须是标识字段。我怎样才能做到这一点呢?字符串数组selectedcertificates包含添加扬声器

时选择的证书。
public bool AddSpeaker(Entities.Speaker speaker, string[] selectedCertifications)
    {
        if (selectedCertifications != null)
        {
            SpeakerCertification speakerCertification = new SpeakerCertification();
            speaker.Certifications = new List<SpeakerCertification>();
            foreach (var certificate in selectedCertifications)
            {
                var certificationToAdd = _ctx.Certifications.Find(int.Parse(certificate));
                speakerCertification.CertificationId = certificationToAdd.Id;
                //speakerCertification.SpeakerId
                speaker.Certifications.Add(speakerCertification);
            }
        }

        _ctx.Speakers.Add(speaker);
        _ctx.SaveChanges();
        return true;
    }

如何添加多对多关系通过实体框架6,在代码

很抱歉打扰了那些完成问题的人,几乎没有任何问题。我只是太蠢了,没有错过。我忘记了实体框架的魔力。我以如下方式实现了add函数

        public bool AddSpeaker(Entities.Speaker speaker, string[] selectedCertifications)
    {
        if (selectedCertifications != null)
        {
            SpeakerCertification speakerCertification = new SpeakerCertification();
            speaker.Certifications = new List<SpeakerCertification>();
            foreach (var certificate in selectedCertifications)
            {
                if (certificate.CompareTo("false")!=0)
                {
                    var certificationToAdd = _ctx.Certifications.Find(int.Parse(certificate));
                    speakerCertification = new SpeakerCertification();
                    speakerCertification.CertificationId = certificationToAdd.Id;
                    speaker.Certifications.Add(speakerCertification);
                }
            }
        }

        _ctx.Speakers.Add(speaker);
        _ctx.SaveChanges();
        return true;
    }