Mapping foreign key in HasOptional().WithOptionalDependent() relation in Entity Framework 6

后端 未结 2 525
没有蜡笔的小新
没有蜡笔的小新 2021-01-08 00:32

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         


        
相关标签:
2条回答
  • 2021-01-08 01:13

    I managed to get a response from the Entity Framework Program Manager after asking on GitHub.

    Unfortunately this is a limitation of EF6. You can not have a foreign key property in a one-to-one relationship, unless it is also the primary key property. This is essentially because EF6 doesn't support alternate keys/unique indexes, so you can't enforce that a non-primary key property is unique. The fact that you can do it when the foreign key property isn't in the entity is a bit of a quirk... but obviously not something we would remove

    0 讨论(0)
  • 2021-01-08 01:33

    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:

    • You preserve your current relationship configuration.
    • Create an authentic one to one relationship.
    • Create an one to many relationship

    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<Contact> Contacts { get; set; }
    }
    

    The configuration would be this way:

     builder.Entity<Contact>()
            .HasOptional(x => x.Student)
            .WithMany(x => x.Contacts)
            .HasForeignKey(x => x.StudentId)
            .WillCascadeOnDelete(true);
    

    Update

    A fourth option could be create two unidirectional relationships:

     builder.Entity<Contact>()
            .HasOptional(x => x.Student)
            .WithMany()
            .HasForeignKey(x => x.StudentId)
            .WillCascadeOnDelete(true);
    
     builder.Entity<Student>()
            .HasOptional(x => x.Contact)
            .WithMany()
            .HasForeignKey(x => x.ContactId)
            .WillCascadeOnDelete(true);
    

    But this option breaks the real relation between the two tables.

    0 讨论(0)
提交回复
热议问题