views:

1170

answers:

1

Ok, what I'm doing is (I think) rather simple.

I have a LINQ-to-SQL data context set up and one of the tables is Users. In the designer, it shows the class as "User" with the source as "dbo.Users". It's access is Public, and I can reach the database to retrieve and update just fine. The class is set to "Use Runtime" for the I/D/U operations.

The problem comes when I try to add a new record.

  1. I have the datagrid set to AutoGenerateColumns ="True"
  2. CanUserAddRows is set to "True"
  3. RowEditEnding event is set to a method.

When I add a record (SubmitChanges() on the data context), nothing happens. It simply does not do the insert. I've checked the local objects at a breakpoint and all indications are that it's indeed there and it does have the correct record that it should be adding.

But wait, there's more.

If I execute Users.InsertOnSubmit() and pass the datagrid's CurrentItem (casted to user), it gives me an error saying "cannot add an entity that already exists" BUT I find that the record has actually been inserted.

Does anyone have a clue?

(FWIW, the backend is SQL2K8 Express)

EDIT:
The code that gives no exception but doesn't add the record either:

         private void UserGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e) 
     { 
         ctx.SubmitChanges(); 
     }

and the code that gives an exception:

        private void UserGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e) 
    { 
        ctx.Users.InsertOnSubmit((User) e.Row.Item); 
        ctx.SubmitChanges(); 
    }
A: 

Do you have any AutoGenerated columns in the database (primary keys, etc)?

I've found in the past with LINQ that if these aren't Ints, and aren't marked as AutoGenerated on the model, that you'll get that sort of error:

Playing with LINQ For SQL in Windows Form Application

In "Part 2: Populating hidden columns/Auto Generated Ids in Linq DataContexts" I talk about my problems with that same error message and behaviour.


Edit to respond to comment:

What's the value of the primary key field in that row? I'm guessing that it's defaulting to "0", which will already exist in the database:

ctx.Users.InsertOnSubmit((User) e.Row.Item);

Have you tried checking to see if you're editing an existing row, and if not, create a new User object, mapp the fields in, and then add that to the Contexts InsertOnSubmit?

Brad Abrams does something similar in the WinForms portion of his SilverLight 3 RTM and .NET RIA Services July Update series - he also shows other ways of doing this sort of thing with a Master-Detail view in Silverlight.

Zhaph - Ben Duguid
The PK is autogenerated, but it is an int and the model also shows it as autogenerated.
Christopher Estep