I have this class:
public class General_File
{
[Key]
public int id { get; set; }
public string FileName { get; set; }
public string Type { get; set; }
public ICollection<Small_File> Small_Files{ get; set; }
}
and this is Small_File
class:
public class Small_File
{
[Key]
public int id { get; set; }
public string Parameter{ get; set; }
public string Name{get; set;}
public int FileId { get; set; }
[ForeignKey("FileId")]
public virtual General_File General_File{ get; set; }
}
I want to modify a row in the General_File
table, modify it, not add a new one, that includes the Small_Files collection corresponding to that row too, it will change too, but I'm not sure of how to deal with this in Entity Framework.... I've been trying with this code.. The local_generalFile.Small_Files
have already the same ids of the files in the table plus some new instances that should be saved in the Small_Files tables too generating its ids..., how can I update that row in General_File and its corresponding Small_Files
collection?
public void SaveFileToDatabase(string type)
{
General_File toModify = _ctx.General_Files.Include("Small_Files")
.Where(s => s.Type== type).OrderByDescending(s => s.id).FirstOrDefault();
toModify.Small_Files = this.local_generalFile.Small_Files;
_ctx.SaveChanges();
}
The code above in the SaveFileToDatabase
method is throwing an exception:
The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.