Why do I need a foreign key in a class in the Entity Framework?

Let's say I have 2 classes: Ninjahas-many NinjaEquipment. Inside NinjaEquipmentme there: public Ninja Ninja { get; set; }. I saw that some people also include, for example, foreign key references: public int NinjaID { get; set; }. What is the point of doing this? Isn't this a simple link Ninjaif I want to switch to a parent-to-one-to-many relationship?

+4
source share
4 answers

What is the meaning of this?

I believe this is the difference between foreign keys and navigation properties.

. , . , ( , ), ( ). , , , .

, . , . . N-Tier. , 1-to-1 1-to-0..1 , .

, . . . , , .

.

+2

, , Entity Framework , .

, , , Entity Framework, . Fluent API, , Entity Framework.

:

public class NinjaEquipmentMap : EntityTypeConfiguration<NinjaEquipment>
{
    public NinjaEquipmentMap
    {
        // Fluent API examples:

        // Describes the relationship between the entities 
        // and the property to use as the foreign key.
        this.HasRequired(t => t.Ninja)
            .WithMany(c => c.NinjaEquipment)
            .HasForeignKey(c => c.NinjaId);

        // I can specify a relationship using a property name
        // that existed in my existing database.
        this.HasRequired(t => t.Ninja)
            .WithMany(c => c.NinjaEquipment)
            .HasForeignKey(c => c.SuperNinjaId);
    }
}

, Entity Framework .

, , , .

// 
// BEFORE
// 
var ninjaEquipment = dbContext.Set<NinjaEquipment>().Find(1);

// We have to load the Ninja record to find out the related Ninja ID
var ninjaId = ninjaEquipment.Ninja.Id;

// 
// AFTER
// 
var ninjaEquipment = dbContext.Set<NinjaEquipment>().Find(1);

// Find out the Ninja equipment ID without having to load the Ninja
var ninjaId = ninjaEquipment.NinjaId;

: o)

+1

, / : , NinjaID NinjaEquipment, ( ) Ninja.

, .. SQL JOIN.

0

All Articles