I have the following data-model in Entity Framework 6.1.3:
using System.Data.Entity;
public class Student
{
public int Id { get; set; }
public virtu
If you want to declare the FK property in the dependent entity in an one to one relationship, I'm afraid you must use it as a PK too. EF Code First requires that PK of the dependent entity must be FK of the relationship too:
public class Contact
{
[Key,ForeignKey("Student")]
public int StudentId { get; set; }
public virtual Student Student { get; set; }
}
But I think this is not what you are looking for. So, I think you have three options here:
By my experience the last one is the most adjusted to what are you trying to achieve (but that is my opinion). In this case you can work with the Fk property as you want, the only is you need to change the Contact
navigation property on Student
by a collection (or omit this nav. property and create an unidirectional relationship):
public class Student
{
public int Id { get; set; }
public virtual ICollection Contacts { get; set; }
}
The configuration would be this way:
builder.Entity()
.HasOptional(x => x.Student)
.WithMany(x => x.Contacts)
.HasForeignKey(x => x.StudentId)
.WillCascadeOnDelete(true);
A fourth option could be create two unidirectional relationships:
builder.Entity()
.HasOptional(x => x.Student)
.WithMany()
.HasForeignKey(x => x.StudentId)
.WillCascadeOnDelete(true);
builder.Entity()
.HasOptional(x => x.Contact)
.WithMany()
.HasForeignKey(x => x.ContactId)
.WillCascadeOnDelete(true);
But this option breaks the real relation between the two tables.