'Adding additional records to existing relationship not working

I am trying to add a new Template to an existing Client, but when I try to add the Template with an existing ClientID, it instead adds a new Template with a new ClientID, not tie the new Template to the existing ClientID

I use the following code to determine if the Template exists with the current Client. If not, I create a Template with the passed in existing Client

public Template GetCurrentTemplate(Client c, string TemplateName)
{
    using (var Context = new mssDBContext())
    {
        List<Template> CurrentTemplates = Context.Templates.Where(x =>  x.TemplateName == TemplateName && x.TemplateClient.Id == c.Id).ToList();
        if (CurrentTemplates.Count == 0)
        {
            Template t = new Template { TemplateName = TemplateName};
            t.TemplateClient = c;
            Context.Templates.Add(t);
            Context.SaveChanges();
            return t;
        }
        else
            return CurrentTemplates[0];
    }
 }

What I get is this :

SQL Table

What I would like is it to add the Template with the existing ClientId of 18, and not add a new Client with an Id of 19 and tie that to the Template.

What am I doing wrong?

Thanks.



Solution 1:[1]

Client c instance you pass to your method is not tracked by the current instance of Context so it adds a new Client and binds template to it. There are few workarounds to the issue if you have TemplateClient_Id property set up on your Template entity you can just set it instead of assigning client by replacing :

t.TemplateClient = c;

with:

t.TemplateClient_Id = c.Id;

Otherwise you can attach Client instance to db context:

Context.Attach(c);
t.TemplateClient = c;
Context.Templates.Add(t);
Context.SaveChanges();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1