What is the syntax for self referencing foreign keys in EF Code First?

后端 未结 3 1972
囚心锁ツ
囚心锁ツ 2020-11-28 23:34

I am trying to reference a foreign key from SpouseId to Id in the Contact table. What is the syntax for doing this? I can\'t seem to find an example. Thanks.

I ha

相关标签:
3条回答
  • 2020-11-28 23:47

    Something like this will work:

    public class Contact
    {
        public int Id {get;set;}
        public string Name {get;set;}
        public int? SpouseId {get;set;}
    
        [ForeignKey("SpouseId")]
        public Contact Spouse {get;set;}
    }
    

    ForeignKeyAttribute has been added to System.ComponentModel.DataAnnotations by CTP5 assembly.

    Update I: CTP5 Bug:

    Due to a bug in CTP5, creating an Independent Self Referencing Associations throws an exception. The workaround is to use Foreign Key Associations instead (which is always recommended regardless).

    Update II: Using Fluent API to Configure a Self Referencing Association:

    You can also use fluent API to achieve this, if you prefer:

    public class Contact
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int? SpouseId { get; set; }                
    
        public Contact Spouse { get; set; }
    }
    
    public class Ctp5Context : DbContext
    {
        public DbSet<Contact> Contacts { get; set; }
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Contact>()
                        .HasOptional(c => c.Spouse)
                        .WithMany()
                        .HasForeignKey(c => c.SpouseId);
        }
    }
    

    Working with the Model:

    using (var context = new Ctp5Context())
    {
        Contact contact = new Contact()
        {
            Name = "Morteza",
            Spouse = new Contact()
            {
                Name = "Code-First"
            }
        };
        context.Contacts.Add(contact);
        context.SaveChanges();
    }
    
    0 讨论(0)
  • 2020-11-28 23:49
    [Table("Move")]
    public class Move
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long ID { get; set; }
        public long? ParentID { get; set; }
    
        [InverseProperty("Children")]
        public virtual Move Parent { get; set; }
        public virtual ICollection<Move> Children { get; set; }
    }
    
    0 讨论(0)
  • 2020-11-28 23:49

    Also, the navigation property Spouse should be virtual to avoid unnecessary JOIN queries:

     public virtual Contact Spouse { get; set; }
    
    0 讨论(0)
提交回复
热议问题