Search code examples
entity-frameworkef-code-firstcode-firstentity-framework-ctp5

How to get rid of foreign key property in EF?


I use EF CTP 5 Code First. If you ask EF to generate database for the model like this it will create appropriate foreign key relationship for you:

public class Parent
{
    public ICollection<Child> MyChildren { get; set; }
}

public class Child 
{ 
    public Parent MyParent { get; set; }
}

Child table gonna have something like MyParent_Id field as a result of such generation. Now I'm having reverse problem - I have a Db schema which I have to build similar simple model for. By similar simple I mean without any explicit foreign key properties. Is any way to do it?

The only way to do the mapping I found looks like this, but it implies having public property MyParentId in the model which I'm trying to avoid. So how to avoid it?

public class Child 
{ 
    [Column("ParentID")]
    public int MyParentId { get; set; }

    [ForeignKey("MyParentId")]
    public Parent MyParent { get; set; }
}  

Thanks in advance


Solution

  • One way is to define your mapping in code rather than using attributes. In your "context" class (the one that derives from DbContext):

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    
        modelBuilder.Entity<Child>()
            .HasRequired(c => c.MyParent)
            .WithMany()
            .Map(c => c.MapKey("MyParent_Id"));
    }
    

    In this case, "MyParent_Id" is the name of the column in the child table rather than the name of any property on the Child class.