I have the two classes:
public class PartDefinition
{
public int Id { get; set; }
[Required]
[MaxLength(10)]
public string PartNumber { get; set; }
[Required]
public virtual Module Module { get; set; }
}
public class Module
{
public int Id { get; set; }
[Required]
[MaxLength(10)]
public string Name { get; set; }
}
Then I try to perform this action:
PartDefinition part = new PartDefinition(partNumber, module);
context.PartDefinitions.Add(part);
context.SaveChanges();
The module that I am passing to the new part definition already exists in the database. However, when I save the new part definition instead of adding the current module as a foreign key it inserts a completely new module.
How can I change this?
Since you do not have any [Key] attributes representing the primary keys in the database; it adds a new module every time. Try marking Id property with [Key] attribute.
Also try to use the same context instance while fetching module and inserting part.