9

I have the following model

public class Foo
{
    public int Id { get; set; }
    public IList<Bar> Bars { get; set; }
}

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

When I generate the database schema from this using EF Code first it creates the following tables:

Foo

  • Id (PK, int, not null)

Bar

  • Id (PK, int, not null)
  • Foo_Id (FK, int null)

Is it possible to change the name of the Foo_Id foreign key using attributes?

EDIT: Here is the version that does what I need:

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

    [ForeignKey("AssignedToBarId")]
    public IList<Bar> Bars { get; set; }
}

public class Bar
{
    public int AssignedToBarId { get; set; }
    public int Id { get; set; }
}

1 Answer 1

8

I think it can be done like below:

protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity.Map(c => c.MapKey(u => u.Id, "AssignedToBarID")); }

Or maybe:

[ForeignKey("AssignedToBarID")]
public IList<Bar> Bars { get; set; }

NOTE: I have not tested neither of them. These are just suggestions.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, your second option did the trick! (must remember to add a property on the Bar type called AssignedToBarId for this to work)
This is a good solution if you don't need bi-directional navigation. NOTE: The name, AssignedToBarID, is a bit confusing for me; AssignedToFooID would be more illustrative.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.