Akbari
Akbari

Reputation: 2409

EF adds extra column for foreign key

I'm using data annotation to have foreign keys. EF successfully builds some columns, but adds extra column for some of the attributes. Here's my class:

public class Class
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Column(TypeName = "BIGINT")]
    public Int64 LiIdH { get; set; }

    [Column(TypeName = "BIGINT"), Index(IsUnique = true)]
    public Int64 LiIdPeriod { get; set; }
    public virtual ZPeriod ZPeriod { get; set; }

    [Column(TypeName = "SMALLINT"), Index(IsUnique = true)]
    public Int16 SWhCode { get; set; }
    public virtual InvtWare InvtWare { get; set; }
}

I'd like to have LiIdPeriod and SWhCode as foreign keys. EF adds LiIdPeriod as a foreign key but for SWhCode it just adds an extra column named InvtWare_SWhCode. How can I solve this problem and have SwhCode as foreign key? I prefer data annotation and attributes to fluent API.

Upvotes: 1

Views: 793

Answers (1)

Jenish Rabadiya
Jenish Rabadiya

Reputation: 6766

You can specify the foreign key to entity framework in two different ways.

  1. Using Data Annotation
  2. Using Fluent API

Using Data Annotation

[Column(TypeName = "SMALLINT"), Index(IsUnique = true)]
public Int16 SWhCode { get; set; }
[ForeignKey("SWhCode")] 
public virtual InvtWare InvtWare { get; set; }

Using Fluent API

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // Assuming one to many relationship
    modelBuilder.Entity<Class>().HasRequired(d =>d.InvtWare).WithMany(d => d.Classes).HasForeignKey(d => d.SwhCode);
}

Upvotes: 2

Related Questions