0

I have two classes as follows.

class Donkey
{
  public Guid Id { get; set; }
}

class Monkey
{
  public Guid Id { get; set; }
  public Donkey Donkey { get; set; }  
}

Now I want to configure the schema so that the relation is set in the database. Using Fluent API, I'll go something like this.

protected override void OnModelCreating(DbModelBuilder model)
{
  base.OnModelCreating(model);
  model.HasDefaultSchema("dbo");
  ...
  model.Entity<Monkey>
    .HasRequired(_ => _.Donkey)
    .WithMany(_ => _.Monkeys)
    .Map(_ => _.MapKey("DonkeyId"));
}

The problem is that now I have to declare a list of monkeys in the donkey. And I don't want to do that. I still want the monkey to point to a donkey using foreign key, so only required status won't do, because I need to specify my custom column name to store the FK pointing to the PK in the table of donkeys.

model.Entity<Monkey>.HasRequired(_ => _.Donkey);

So, the above lacks the mapping (and it doesn't compile when I just add it). Is there a way to work around it without actually changing the definition of Donkey class?

Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438

1 Answers1

1
modelBuilder.Entity<Monkey>()
            .HasRequired(x => x.Donkey)
            .WithMany();
SteppingRazor
  • 1,222
  • 1
  • 9
  • 25
  • Interesting. I didn't realize there was such overload. Now, to map to a custom named column, can I simply use *MapKey* as I've shown in my question or are there any other issues to consider sprung from invokation of a different method? – Konrad Viltersten Apr 09 '16 at 19:03
  • You can add another overload like `.Map(x => x.MapKey("DonkeyId"));` or if you add another column to `Monkey` class, you can use `.HasForeignKey(x => x.DonkeyId);` – SteppingRazor Apr 09 '16 at 19:08
  • By the way, this was a great answer, so you're more than welcome to give it an equally great whack at [this one](http://stackoverflow.com/questions/36521800/how-to-declare-a-one-to-many-in-fluent-api-so-that-its-not-required). It's probably even easier. – Konrad Viltersten Apr 09 '16 at 19:43