my current project is based on Entity Framwork code-first. I have three types: Task, TaskType and Module.
public class Task
{
public int ID { get; set; }
public Module Module { get; set; }
public TaskType Type { get; set; }
}
public class TaskType
{
public int ID { get; set; }
public string Name { get; set; }
}
public class Module
{
public int ID { get; set; }
public string Name { get; set; }
}
There are foreign key relations defined inside the table for the Task-type.
My problem is that when I try to create a new Task-object linked to already available TaskType and Module objects (ID = 1), those objects are created as new rows in their corresponding tables.
TaskRepository repo = new TaskRepository();
Task task = new Task();
task.Module = Modules.SingleOrDefault(m => m.ID == 1);
task.Type = TaskTypes.SingleOrDefault(t => t.ID == 1);
Tasks.Add(task);
This creates a new row in my TaskType-table and in my Modules-table as well instead of just using the already available TaskType-ID and Module-ID.
I hope I made clear what my problem is 😉
Thanks in advance for your help. I appreciate it.
Regards,
Kevin
If you don’t use the same context instance to load related entities you cannot simply add them to the new entity and expect that existing records in the database will be used. The new context doesn’t know that these instances exist in the database – you must to say it to the context.
Solutions:
AddedtoUnchangedExample for 1:
Example for 2:
Example for 3:
Example for 4: