DataTable object initializer with Primary Key

Tea With Cookies

I'm having difficulty initializing a DataTable specifying the Columns and PrimaryKey with an object initializer:

private DataTable _products = new DataTable
    {
        Columns = { { "Product", typeof(string) }, { "Lot", typeof(string) }, { "Qty", typeof(int) } },
        PrimaryKey = Columns[0]  //Columns doens't exist in the current context
    };

Is there a way to make it work?

Tim Schmelter

No, you cannot use object initializer syntax if you want to use an object in it which is also initialized in it. But that wouldn't make much sense either.

Instead use the constructor since that is the appropriate place:

private DataTable _products;

public void ClassName()
{
    _products = new DataTable
    {
        Columns = { { "Product", typeof(string) }, { "Lot", typeof(string) }, { "Qty", typeof(int) } }
    };
    _products.PrimaryKey = new[] { _products.Columns[0] };
}

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Primary Key and Composite Key

분류에서Dev

Select record by Primary Key

분류에서Dev

jsf - foreign key in datatable

분류에서Dev

How to add primary key to a view?

분류에서Dev

set two fields as primary key

분류에서Dev

Overpassing SqlBulkCopy - Violation of Primary Key

분류에서Dev

Using String values for primary key

분류에서Dev

Sqlite JPA Primary Key error

분류에서Dev

Generating Primary key without set it as key

분류에서Dev

Postgresql and primary key, foreign key indexing

분류에서Dev

Compile error / Object initializer with Type ChartArea

분류에서Dev

Oracle IDENTITY 열 대 PRIMARY KEY

분류에서Dev

DynamoDB - how to query by something that is not the primary key

분류에서Dev

MS Access query table without primary key

분류에서Dev

Autoincrement Primary key generate weird values

분류에서Dev

JPA: persisting entity with composite primary key

분류에서Dev

Skipping SQLite operation if primary key already in table

분류에서Dev

how to get last inserted primary key

분류에서Dev

How to create a table with _id as composite primary key?

분류에서Dev

sqlite constraint exception primary key must be unique

분류에서Dev

Cassandra primary key design to cater range query

분류에서Dev

django redirect with full url and primary key in template

분류에서Dev

Hibernate Primary Foreign Key 필드

분류에서Dev

Django unique_together on primary key

분류에서Dev

INT PRIMARY KEY와 INTEGER PRIMARY KEY SQLite의 차이점

분류에서Dev

Django CharField primary key doesn't work, creating rowid primary key automatically

분류에서Dev

Saving Related Objects with Primary Object in Parse

분류에서Dev

How to reset the primary key id in ruby on rails 6?

분류에서Dev

Insert column to make the primary key in T-SQL

Related 관련 기사

뜨겁다태그

보관