Reputation: 2680
I have two poco's
public class Person {
[Key]
public virtual int Id { get; set; }
public virtual int? AtendeeId { get; set; }
[ForeignKey("Id")]
public virtual Atendee Atendeed { get; set; }
}
public class Atendee {
[Key]
public virtual int Id { get; set; }
public virtual int PersonId { get; set; }
public virtual Person Person { get; set; }
}
For some reason this creates a FK from atendee to person using the ID column of atendee instead of personId. What would be the correct way of declaring this?
Here is the FK generated:
ALTER TABLE [dbo].[Atendees] WITH CHECK ADD CONSTRAINT [FK_dbo.Atendees_dbo.People_Id] FOREIGN KEY([Id])
REFERENCES [dbo].[People] ([Id])
Upvotes: 0
Views: 49
Reputation: 3037
You only list the 'opposite' foreign key for a collection, ie for a 1-N relation.
You seem to have a 1-1 relation.
//[ForeignKey("Id")]
[ForeignKey("AtendeeId")] // or just omit this
public virtual Atendee Atendeed { get; set; }
public class Person {
[Key]
public virtual int Id { get; set; }
[ForeignKey("Atendeed")] // refer to the property
public virtual int? AtendeeId { get; set; }
public virtual Atendee Atendeed { get; set; }
}
But you should consider using the fluent notation in override OnModelBuilding, that usually gives you more control.
Upvotes: 3