Simple many to many relationship

Here all the cases that I am trying to accomplish
- case number 1. Both the file and the category are new
- Case number 2. The file is not new and category is not new.
- Case number 3. The file is new but the category is not new
- Case number 4. The file is new but the categirt is not new.
Case Number 1 solution: everything works fine here
using (MyContext DbCtx = new MyContext())
{
var FileCategory = new FileCategory {
Active=true,
Category="W",
File = new List<File>()
};
var File = new File
{
FileName = "a",
FileTypeId = 1,
RevisionDate = DateTime.Now,
UploadDate = DateTime.Now,
FileCategory = new List<FileCategory>()
};
DbCtx.FileCategory.Add(FileCategory);
FileCategory.File.Add(File);
DbCtx.SaveChanges();
}
Case Number 2: I get an error:NullReferenceException (
I think FileCategory navigational property is null from the MyExistingFile. Not sure is lazy loading is getting the best of me here.
using (MyContext DbCtx = new MyContext())
{
var MyExistingFile = DbCtx.File.Find(1);
var MyExistingCategory = DbCtx.FileCategory.Find(1);
//with the line below i am trying to say we dint change anything on File since it already exist
DbCtx.Entry<File>(MyExistingFile).State = EntityState.Unchanged;
//I am just trying to add the category to a file. Since a file can multiple categories.
MyExistingFile.FileCategory.Add(MyExistingCategory);
DbCtx.SaveChanges();
}
I am guessing I will be able to solve the rest once someone shows me why case number 2 is wrong.
Update: Solution was given by Slauma
I added virtual to all my poco properties and navigational properties like this
public class FileCategory
{
[Key]
public virtual int FileCategoryId { get; set; }
public virtual string Category { get; set; }
public virtual bool Active { get; set; }
public virtual ICollection<File> File { get; set; }
}
Then I was able to write this and it worked for case number 2
using (MyContext DbCtx = new MyContext())
{
var MyExistingFile = DbCtx.File.Find(1);
var MyExistingCategory = DbCtx.FileCategory.Find(1);
MyExistingFile.FileCategory.Add(MyExistingCategory);
DbCtx.SaveChanges();
}
Just create an empty list:
It’s actually better to avoid lazy loading in this scenario because it would load the
FileCategorycollection from the database. But you don’t need this collection to create the new relationship.Manually setting the state to
Unchangedis not necessary, so I removed that line.