实体框架6多对多添加在双方都不起作用

时间:2016-05-08 14:38:59

标签: c# entity-framework entity-framework-6

说我有以下型号:

public class Letter 
{
   public int Id {get; set;}

   public List<Folder> Folders {get;set;}
}

public class Folder 
{
    public int Id {get; set;}

    public List<Letter> Letters {get; set;}
}

 public class ProjectDbContext : DbContext
 {
       public class ProjectDbContext()
      {
             Configuration.LazyLoadingEnabled = false;
      }
  }

关系是从字母侧配置如下:

 public class LetterConfiguration : EntityTypeConfiguration<Letter> 
{
       public LetterConfiguration()
     {
           HasMany(x =>             x.Folders).WithMany().Map(configuration =>
         {
             configuration.MapLeftKey(LetterId);
             configuration.MapRightKey(FolderId);
         }
     }
 }

现在的例子: 与种子文件夹的空数据库。 如果我一个接一个地调用这两种方法,我根本就没有信件:

 public class LettersDataAccess()
{
      public void AddLettersToFolder(int[] letters, Folder folder
     {
            var databaseLetters = _DbSet.Include(l => l.Folders).where(x => letters.contains(x.Id));

            foreach (var letter in databaseLetters)
            { 
                  // The folder is one I receieved erlier from the database, and therefore should be tracked
                  letter.Folders.Add(folder)
            }

            SaveChanges();
      }
}

 public class FoldersDataAccess()
{
      public List<Letter> GetFolderLetters(int folderId)
     {
             Folder folder =_dbSet.Include(f =>  f.Letters).First(f => f.Id ==folderId)

            // returns no results
           return folder.Letters;
      }
}

现在我的问题是: 如果我添加一个字母并将其文件夹列表设置到我系统中的现有foldera,这封信会自动添加到这些文件夹的字母列表中吗?

或者添加总是双面的?这应该怎么样?我希望它在第一种方式起作用,但似乎没有。

我希望有人能在这里指导我。

由于

0 个答案:

没有答案