LinqToSQL InsertOnSubmit Issue

330 Views Asked by At

I've class contact that has associate with class account and city. City has associate with class state, when I try to insert new contact data, the associated class is inserted too. How can this happen ? And how to fix it ?

Method InsertOnSubmit

    public void InsertOnSubmit<T>(T data) where T : class
    {
        lock (_lockObj)
        {
            using (DataModel dx = new DataModel(this._adapter.ConnectionString))
            {
                dx.DeferredLoadingEnabled = false;
                dx.GetTable<T>().InsertOnSubmit(data);
                dx.SubmitChanges();
            }
        }
    }

Add new contact

InsertOnSubmit(new Contact { Name = this.Name, Account = Session.Account, City = this.CurrentCity });

Note: object city, account, and state is from different datacontext. I use SQL Server Compact 3.5 as Database Server.

Log from console when dx.SubmitChanges() is fired

INSERT INTO [State]([Name])
VALUES (@p0)
-- @p0: Input String (Size = 0; Prec = 0; Scale = 0) [Center America]
-- Context: SqlProvider(SqlCE) Model: AttributedMetaModel Build: 4.0.30319.1

SELECT CONVERT(Int,@@IDENTITY) AS [value]
-- @ROWCOUNT: Input Int32 (Size = 0; Prec = 0; Scale = 0) [1]
-- Context: SqlProvider(SqlCE) Model: AttributedMetaModel Build: 4.0.30319.1

INSERT INTO [City]([StateId], [Name])
VALUES (@p0, @p1)
-- @p0: Input Int32 (Size = 0; Prec = 0; Scale = 0) [10]
-- @p1: Input String (Size = 0; Prec = 0; Scale = 0) [Los Angeles]
-- Context: SqlProvider(SqlCE) Model: AttributedMetaModel Build: 4.0.30319.1

SELECT CONVERT(Int,@@IDENTITY) AS [value]
-- @ROWCOUNT: Input Int32 (Size = 0; Prec = 0; Scale = 0) [1]
-- Context: SqlProvider(SqlCE) Model: AttributedMetaModel Build: 4.0.30319.1

INSERT INTO [Contact]([AccountId], [CityId], [Name])
VALUES (@p0, @p1, @p2)
-- @p0: Input Int32 (Size = 0; Prec = 0; Scale = 0) [1]
-- @p1: Input Int32 (Size = 0; Prec = 0; Scale = 0) [18]
-- @p2: Input String (Size = 0; Prec = 0; Scale = 0) [Sarah]
-- Context: SqlProvider(SqlCE) Model: AttributedMetaModel Build: 4.0.30319.1

SELECT CONVERT(Int,@@IDENTITY) AS [value]
-- @ROWCOUNT: Input Int32 (Size = 0; Prec = 0; Scale = 0) [1]
-- Context: SqlProvider(SqlCE) Model: AttributedMetaModel Build: 4.0.30319.1

Regards,

Brian

0

There are 0 best solutions below