Linq to SQL not inserting data onto the DB

Posted by Jesus Rodriguez on Stack Overflow See other posts from Stack Overflow or by Jesus Rodriguez
Published on 2010-03-18T16:18:22Z Indexed on 2010/03/18 16:21 UTC
Read the original article Hit count: 542

Filed under:
|
|

Hello!

I have a little / weird behaviour here and Im looking over internet and SO and I didn't find a response.

I have to admit that this is my first time using databases, I know how to use them with SQL but never used it actually.

Anyway, I have a problem with my app inserting data, I just created a very simple project for testing that and no solution yet.

I have an example database with Sql Server

Id - int (identity primary key) Name - nchar(10) (not null)

The table is called "Person", simple as pie.

I have this:

static void Main(string[] args)
    {
        var db = new ExampleDBDataContext {Log = Console.Out};

        var jesus = new Person {Name = "Jesus"};

        db.Persons.InsertOnSubmit(jesus);
        db.SubmitChanges();

        var query = from person in db.Persons select person;

        foreach (var p in query)
        {
            Console.WriteLine(p.Name);
        }
    }

As you can see, nothing extrange.

It show Jesus in the console. But if you see the table data, there is no data, just empty. I comment the object creation and insertion and the foreach doesn't print a thing (normal, there is no data in the database)

The weird thing is that I created a row in the database manually and the Id was 2 and no 1 (Was the linq really playing with the database but it didn't create the row?)

There is the log:

INSERT INTO [dbo].Person

VALUES (@p0)

SELECT CONVERT(Int,SCOPE_IDENTITY()) AS [value]

-- @p0: Input NChar (Size = 10; Prec = 0; Scale = 0) [Jesus]

-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.30729.4926

SELECT [t0].[Id], [t0].[Name] FROM [dbo].[Person] AS [t0]

-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.30729.4926

I am really confused, All the blogs / books use this kind of snippet to insert an element to a database.

Thank you for helping.

© Stack Overflow or respective owner

Related posts about sql-server

Related posts about linq-to-sql