pgerchev
pgerchev

Reputation: 187

Configure unidirectional one to many relationship EF6

I have two entities as the following:

public class FirstEntity
{
    public int Id { get; set; }

    public ICollection<SecondEntity> SecondEntityCollection { get; set; }
}

public class SecondEntity
{
    [Key]
    [Column(Order = 0)]
    public int FirstEntitySomeId { get; set; }

    [Key]
    [Column(Order = 1)]
    public int SecondEntityId { get; set; }
}

I want to generate a migration to add SecondEntity to the database using EF6. The problem is that EF generates the migration as following:

CreateTable("dbo.SecondEntity",
        c => new
        {
            SecondEntityId = c.Int(nullable: false),
            FirstEntitySomeId = c.Int(nullable: false),
            FirstEntity_Id = c.Int(),
        })
        .PrimaryKey(t => new {t.SecondEntityId, t.FirstEntitySomeId})
        .ForeignKey("dbo.FirstEntity", t => t.FirstEntity_Id)
        .Index(t => t.FirstEntity_Id);

It automatically generates a new column FirstEntity_Id as a foreign key since FirstEntitySomeId does not follow the conventions (and I want to keep the name that way).

How can I force EF to not generate a new column but rather use FirstEntitySomeId as an FK instead? Note that the relationship is unidirectional. SecondEntity does not contain a navigation property of type FirstEntity (and it shouldn't).

Upvotes: 1

Views: 689

Answers (1)

Kinetic
Kinetic

Reputation: 2650

Using fluent mapping, you could do something like this:

modelBuilder.Entity<FirstEntity>()
    .HasMany(m => m.SecondEntityCollection)
    .WithRequired()
    .HasForeignKey(m => m.FirstEntitySomeId);

If you're using attributes, you can set the foreign key this way :

public class FirstEntity
{
    public int Id { get; set; }
    [ForeignKey("FirstEntitySomeId")]
    public ICollection<SecondEntity> SecondEntityCollection { get; set; }
}

Upvotes: 6

Related Questions