如何在实体框架和事务中插入属性多对多关系

时间:2015-08-06 08:40:08

标签: asp.net entity-framework

我有一张桌子申请 -

ID

名称

SrtusID -

我还有一张桌子 ApplicantLanguages

ID

ApplicantID

LanguageID(多对多关系)

所以我的问题是当我尝试添加一个申请人和他的语言时 - 不应该是交易中的那个并且是正确的方法

提前谢谢!

public void AddApplicant(string FirstName, string  LastName, int StatusId,int AddressId, List<int>SelectedLanguages)
        {
            Applicant newApplicant = new Applicant { Name = FirstName, LastName = LastName,AddressesId = AddressId,StatusesId=StatusId };
            foreach (var item in SelectedLanguages)
            {
                newApplicant.Languages.Add(testEntity.Languages.Where(x=>x.id==item).FirstOrDefault());
            }
            testEntity.Applicant.Add(newApplicant);
            testEntity.SaveChanges();

1 个答案:

答案 0 :(得分:0)

有下一个模型:

public class Applicant
{

    public int Id {get;set;}

    public string Name {get;set;}

    public virtual ICollection<ApplicantLanguage> Languages {get;set;}
}

public class ApplicantLanguage{

    public int Id{get;set;}

    [ForeignKey("Applicant")]
    public int ApplicantId{get;set;}

    public virtual Applicant {get;set;}

    [ForeignKey("Language")]
    public int LanguageId{get;set;}

    public virtual Language {get;set;}
}

你可以添加下一步

public void AddApplicant(string FirstName, string  LastName, int StatusId,int AddressId, List<int>SelectedLanguages)
{
    Applicant newApplicant = new Applicant { Name = FirstName, LastName = LastName,AddressesId = AddressId,StatusesId=StatusId };

    newApplicant.Languages.Add(SelectedLanguages.Select(langId=>new ApplicantLanguage{Applicant = newApplicant, LanguageId = langId})
    testEntity.Applicant.Add(newApplicant);
    testEntity.SaveChanges();
}