So, I’m fighting a migraine. I cannot see the solution to this problem.
I have a table named dr405 that is preloaded with data. My application only updates existing rows in the table with information.
I have a service method called Save in this save method I set the state in my context for the given DR405 entity to modified and then call SaveChanges. This works as expected.
Now I’m trying to add in another step where I have a model called DR405files which is a child to DR405 using a 1:N relationship. I want to call a method GetUploadedFiles() that will check a directory thats name matches the dr405 primary key for files, then insert into the table dr405files the file names.
I’ve set up the relationships between the Models in both the classes and in the Database. I’ve even written code that will correctly insert the filenames into dr405files. However, after I run the application once, it throws an Null Reference exception in consecutive runs on p.
Any help would be greatly appreciated
public void Save(DR405DBContext context, dr405 obj)
{
obj.ModDate = DateTime.Now;
context.Entry(obj).State = EntityState.Modified;
var uploadedFiles = this.GetUploadedFiles(obj.TangiblePropertyId);
if (uploadedFiles !=null && uploadedFiles.Count > 0)
{
uploadedFiles.ForEach(p=> {
var item = new dr405files { TangiblePropertyId = obj.TangiblePropertyId, FileName = p }; <---Exception Occurs here.
if(!obj.dr405files.Contains(item))
{
var fileItem = new dr405files { TangiblePropertyId = obj.TangiblePropertyId, FileName = p };
context.Entry(fileItem).State = fileItem.FileId == 0 ? EntityState.Added : EntityState.Modified;
}
});
}
context.SaveChanges();
}
public List<String> GetUploadedFiles(String id)
{
var saveLocation = Path.Combine(DR405Service.SavePath + GetDR405ById(new DR405DBContext(), id).TangiblePropertyId);
Directory.CreateDirectory(saveLocation);
return Directory.GetFiles(saveLocation).ToList();
}
public class dr405files
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int FileId { get; set; }
public String TangiblePropertyId { get; set; }
public String FileName { get; set; }
}
public class dr405
{
[Key]
public String TangiblePropertyId { get; set; }
public DateTime CreateDate { get; set; }
public DateTime ModDate { get; set; }
public String PreparerName { get; set; }
...
}
I was trying to load from obj.dr405files. Which was not instantiated yet. I changed the code to pull from context.dr405files and….Voila!
New Code