Configure unidirectional one to many relationship EF6

时间:2016-08-31 17:57:34

标签: c# database entity-framework-6

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).

1 个答案:

答案 0 :(得分:3)

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; }
}