How to get the particular value of column using the primary key - entity framework?

entity framework get entity by name
entity framework find by id
entity framework core find by column
entity framework find by non primary key
entity framework find vs where
entity framework delete
entity framework find multiple keys
entity framework update

I have different tables. For example Table 1 contains the name of Persons Table 2 contains the Country name and Person Id

Table 1:
PersonId     PersonName
1            John
2            Smith
3            Kelly


Table 2:
LocationId   Continent      Country     PersonId
1            Asia           Japan       1
2            Asia           China       2

// There is C# method where PersonId should be passed.. suppose id=2 is passed

var person = await _repository.Person.FirstOrDefaultAsync(x => x.PersonId == id); //This find Smith from DB
var location = await _repository.Location.FirstOrDefaultAsync(x => x.LocationId == person.PersonId);   
// location variable will get all values of second row from Table 2 i.e LocationID=2, Continent=Asia, Country=China, PersonId=2
// but i just need value of Country column i.e China of PersonId=2

// Though I can get CountryName from this -- have to write below extra code for that
var country = location.Country;   // this will get Country = China

How can I achieve this in a single line?

// something like
var location = await _repository.Location.FirstOrDefaultAsync(x => x.LocationId == person.PersonId).Country();

Use Select

var country = await _repository.Location.Where(x => x.LocationId == person.PersonId).Select(l => l.Country).FirstOrDefault();

Querying and Finding Entities, The Find method on DbSet uses the primary key value to attempt to find an only be made if the entity with the given key is not found in the context. Entity Framework allows your entities to have composite keys - that's a key Note that when you have composite keys you need to use ColumnAttribute or  object GetPrimaryKeyValue(DbEntityEntry entry) { var objectStateEntry = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity); return objectStateEntry.EntityKey.EntityKeyValues[0].Value; } If there is more than one key then you should iterate over the EntityKeyValues property.

You should look at creating a Navigation Property on the person object so EF can automatically map the relationship for you. You can then choose to either Lazy load, or eager load the country in one query with include.

Owned Entity Types, How to configure owned entity types or aggregates when using Entity It is used as a property of the Order type to specify the shipping address for a particular order. Since the foreign key is not part of the primary key its values can be changed By default, EF Core will name the database columns for the  I get the following error: Cannot insert the value NULL into column 'Id', table 'FooDatabase.dbo.Foos'; column does not allow nulls. INSERT fails. Dapper correctly assumes, by convention, that Id is the primary key, but it incorrectly assumes that it is an identity column. How can I indicate that it is not an identity column?

//First Method :

Entity await _repository = new Entity() // object of your entity.
var Result = (from a in await _repository.Person.Where(a=>a.PersonId == id)
              from b in await _repository.Location.Where(b=>b.PersonId=a.PersonId)
              select new 
              {
                 a.PersonId,a.PersonName,b.Country
              }).SingleOrDefault();
Result.Country; // Here you can get country,also get other values PersonName,PersonId

//Second Method :

Entity await _repository = new Entity() // object of your entity.
var Result = (from a in await _repository.Location.Where(a=>a.PersonId == id)select 
              a.Country).SingleOrDefault(); //other wise you can select 'a'.  
Result.Country; // Here you can get country

8 Ways to use the features of your database with Hibernate, to entity attributes; Generate unique primary key values with sequences; Use autoincremented columns as primary keys; Map custom and database-specific  Now in this article I will show how to create a Primary Key and Foreign Key using the code first approach in MVC with Entity Framework. Here I will create 2 tables, Students and Course. Both tables will have a Primary Key and the Student table will reference the course table with CourseID as the Foreign Key.

Configure Property Mappings using Fluent API in EF Code-First, Learn how to configure the properties of an entity with the database table using Using Fluent API, you can change the corresponding column name, type, size, do not follow the Code-First convention for primary key because they don't have Id to use different methods to configure a particular property, as shown below. At least in EF Core 2.1 you can get the key this way: var entry = dbContext.Entry(entity); object[] keyParts = entry.Metadata.FindPrimaryKey() .Properties .Select(p => entry.Property(p.Name).CurrentValue) .ToArray(); This allows you to get the key which is created as a shadow property.

Deleting data via the DbContext, The approach that you adopt to deleting entities via the DbContext depends on The only property that the stub requires is the primary key value. A fully defined relationship will have a cascading referential constraint set to Delete or SQL Queries using Entity Framework Core · The Fluent API HasColumnType Method. Updating primary key columns is not a good practice with EntityFramework. It confuses EF because it changes the identity of the object, and makes keeping the in-memory copy and the in-database copy of the data in sync very problematic. So it's not allowed. Just don't update primary keys. Instead delete one row and insert a new one.

Modifying data via the DbContext, Update method (which is new in EF Core); using the DbContext. will issue an SQL statement updating all property values (apart from the primary key value). If the related entity doesn't have a key value assigned, it will be marked as SQL Queries using Entity Framework Core · The Fluent API HasColumnType Method. Here Mudassar Ahmed Khan has explained with an example, how to get ID of last inserted record using Entity Framework in ASP.Net MVC Razor. When the Form is submitted, the value of the submitted Form fields will be fetched using Entity Framework Model class object and will be inserted into database using Entity Framework.

Comments
  • By giving your Person class a Country property and Include()ing that navigation property. What have you tried?