Alex Rivera | Logout

LINQ to SQL entity column name attribute ignored with guid primary key

Asked 2009-07-01T04:29:38.510
11

I was working with a simple entity class with LINQ to SQL (SQL Server 2005 SP3 x64).

[Table( Name="TBL_REGISTRATION" )]
public sealed class Registration : IDataErrorInfo
{
    [Column( Name = "TBL_REGISTRATION_PK", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert )]
    public Guid RegistrationID { get; private set; }
    /* other properties ommited for brevity */
}

There are only two somewhat interesting things here:

  1. The class and property names aren't the same as the table and column names
  2. The primary key is a Guid (uniqueidentifier)

Here's what the table looks like:

 create table dbo.TBL_REGISTRATION
    (
    TBL_REGISTRATION_PK uniqueidentifier primary key clustered
        rowguidcol
        default newid(),
    /* other columns ommited for brevity */ 
    )

When I attach this entity to my table and submit changes on my DataContext, the LINQ stack throws back a SqlException:

SqlException (0x80131904): Invalid column name 'RegistrationID'

LINQ seems to be ignoring the Column( Name = "TBL_REGISTRATION_PK" ) attribute on my RegistrationID property. I spent a while futzing with different attribute decorations trying to get it to work. In the end I settled on a private TBL_REGISTRATION_PK property to wrap my RegistrationID property to make LINQ happy.

[Table( Name="TBL_REGISTRATION" )]
public sealed class Registration : IDataErrorInfo
{
        public Guid RegistrationID { get; private set; }
        [Column( IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert )]
        private Guid TBL_REGISTRATION_PK { get { return RegistrationID; } set { RegistrationID = value; } }
    /* other properties ommited for brevity */
}

This works.

Why didn't it work the first way? Am I doing something wrong here or is this a LINQ defect?

Edit
Report

1 Answer

0

Have you tried using the Storage property?

[Table( Name="TBL_REGISTRATION" )]
public sealed class Registration : IDataErrorInfo
{
        [Column( Name="TBL_REGISTRATION_PK", Storage="_RegistrationID", IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert )]
        public Guid RegistrationID { get { return _RegistrationID; } set { _RegistrationID = value; } }

        private Guid _RegistrationID;
    /* other properties ommited for brevity */
}

See also Attribute-Based Mapping (LINQ to SQL)

answered 2009-07-08T16:34:02.760

Your Answer