Get Identity Column Name At Runtime in LINQ to SQL

This is a small post but it might be helpful.

I have created a Table Called “Test” in Database with 2 Columns.
1. CategoryId -> Primary Key, Identity Column, Not Null
2. Name -> nVarchar(100), Not Null

Drag and Drop that table on LinQToSql Context.dbml file.

In Code Behind:

protected void Page_Load(object sender, EventArgs e)
    {
        using (var context = new Context())
        {
            ltIdentity.Text = context.Mapping.GetMetaType(typeof(Test)).DBGeneratedIdentityMember.Name;
        }
    }

ltIdentity is a Literal on the webpage.
Click here to download the code.

This entry was posted in C#. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>