Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Core Find and Composite Key

The Find() method takes an array of objects describing the primary key you're attempting to find. The documentation is unclear as to how to handle composite primary keys. I tried searching the GitHub repository, but was unable to find the source code for the Finder.Find() method.

For example, I've used the fluent API to define the following composite primary key:

modelBuilder.Entity<Article>()
    .HasKey( x => new { x.CommunityID, x.ArticleID } );

Do I call Find() like this:

Find( new object[] {1, 2} );

or like this:

Find( new object[] { new {CommunityID = 1, ArticleID = 2} } );

If it's the first approach, is the order of the parameters the same as the order of properties defined on the fluent API anonymous object?

like image 887
Mark Olbert Avatar asked Dec 23 '17 02:12

Mark Olbert


People also ask

How do you get a composite key?

A composite key is made by the combination of two or more columns in a table that can be used to uniquely identify each row in the table when the columns are combined uniqueness of a row is guaranteed, but when it is taken individually it does not guarantee uniqueness, or it can also be understood as a primary key made ...

How do you use Find in EF core?

EF Core Find method finds a record with the given primary key values. If the entity is already in the context (because of a previous query), then the Find method returns it. The Find method sends the query to the database if it does not find it in the context.

What is composite key in Entity Framework?

You can also configure multiple properties to be the key of an entity - this is known as a composite key. Composite keys can only be configured using the Fluent API; conventions will never set up a composite key, and you can not use Data Annotations to configure one.

How do I create a composite primary key in Entity Framework Core?

Entity Framework Core supports composite keys - primary key values generated from two or more fields in the database. Composite keys are not covered by conventions or data annotation attributes. The only way to configure composite keys is to use the HasKey method.


1 Answers

Find has a signature of: params object[] keyValues

No need to pass in an array, just each key separately:

.Find(1, 2);

If it's the first approach, is the order of the parameters the same as the order of properties defined on the fluent API anonymous object?

Yes, you'll need to pass in the PKs in the same order as defined within your fluent API map.

like image 81
d.moncada Avatar answered Sep 30 '22 21:09

d.moncada