Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare "Key" fields in C# anonymous types?

In VB.NET I'm used to doing things like this when creating anonymous types (VB.NET anonymous types include the notion of Key Fields):

Dim prod1 = New With {
    Key .Name = "paperclips",
    Key .Price = 1.29,
    .OnHand = 423
}

However, I haven't been able to find any way of doing this in C#, since it appears the Key keyword is not supported.

Is there any way to indicate in C# that I only want to compare some of the fields in anonymous type when looking for equality?

like image 221
Daniel Avatar asked Jan 21 '13 02:01

Daniel


People also ask

How do I add a field to a primary key?

Create a primary key to associate data between multiple tables. In the Navigation Pane, right click a table, and select Design View. Select the field or fields you want to use as the primary key. Select Design > Primary Key.

Which field is suitable for declaring primary key?

The customer ID field is the primary key. Access automatically creates an index for the primary key, which helps speed up queries and other operations. Access also ensures that every record has a value in the primary key field, and that it is always unique.

How do you define a key for an entity?

An entity key is a property or a set of properties of an entity type that are used to determine identity. The properties that make up an entity key are chosen at design time. The values of entity key properties must uniquely identify an entity type instance within an entity set at run time.

How do you explicitly set a property as a primary key?

Configuring a primary key By convention, a property named Id or <type name>Id will be configured as the primary key of an entity. Owned entity types use different rules to define keys. You can configure a single property to be the primary key of an entity as follows: Data Annotations.


2 Answers

There is nothing like that in C#. In C#, all properties of anonymous types are read-only and participate in equality comparisons.

If you want to do something like this in C#, you will need to create your own (named) type.

like image 170
svick Avatar answered Sep 20 '22 19:09

svick


There is no Key equivalent in c#.

like image 24
Ely Avatar answered Sep 18 '22 19:09

Ely