Linq to SQL duplicating entry when referencing FK

Posted by Oscar on Stack Overflow See other posts from Stack Overflow or by Oscar
Published on 2010-12-27T23:47:49Z Indexed on 2010/12/27 23:54 UTC
Read the original article Hit count: 227

Filed under:
|

Hi! I am still facing some problems when using LINQ-to-SQL. I am also looking for answers by myself, but this problem is so akward that I am having problems to find the right keywords to look for it.

I have this code here:

public CustomTask SaveTask(string token, CustomTask task)
    {
        TrackingDataContext dataConext = new TrackingDataContext();

        //Check the token for security
        if (SessionTokenBase.Instance.ExistsToken(Convert.ToInt32(token)) == null) return null;

        //Populates the Task - the "real" Linq to SQL object            
        Task t = new Task();
        t.Title = task.Title;
        t.Description = task.Description;

//****The next 4 lines are important****
        if (task.Severity != null)
            t.Severity = task.Severity;
        else
            t.SeverityID = task.SeverityID;

        t.StateID = task.StateID;

        if (task.TeamMember != null)
            t.TeamMember = task.TeamMember;
        else
            t.ReporterID = task.ReporterID;

        if (task.ReporterTeam != null)
            t.Team = task.ReporterTeam;
        else
            t.ReporterTeamID = task.ReporterTeamID;

        //Saves/Updates the task
        dataConext.Tasks.InsertOnSubmit(t);
        dataConext.SubmitChanges();

        task.ID = t.ID;

        return task;
    }

The problem is that I am sending the ID of the severity, and then, when I get this situation:

DB State before calling the method:

ID Name 1 high 2 medium 3 low

Call the method selecting "medium" as severity

DB State after calling the method: ID Name 1 high 2 medium 3 low 4 medium

The point is: -It identified that the ID was related to the Medium entry (and for this reason it could populate the "Name" Column correctly), but if duplicated this entry. The problem is: Why?!!

Some explanation about the code: CustomTask is almost the same as Task, but I was having problems regarding serialization as can be seen here I don't want to send the Severity property populated because I want my message to be as small as possible.

Could anyone clear to my, why it recognize the entry, but creates a new entry in the DB?

© Stack Overflow or respective owner

Related posts about Silverlight

Related posts about linq-to-sql