Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3808830
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 19, 20262026-05-19T15:12:36+00:00 2026-05-19T15:12:36+00:00

I am trying to reference a foreign key from SpouseId to Id in the

  • 0

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 have a class like this:

public class Contact
{
    public int Id {get;set;}
    public string Name {get;set;}
    public int? SpouseId {get;set;}
}

EDIT1
Per the link provided by Joel Cunningham and the answer from Morteza I have added some additional code.

ContactMap.cs

public partial class ContactMap : EntityTypeConfiguration<Contact>
{
  public ContactMap()
     {
       this.ToTable("Contact");
       this.HasKey(c => c.Id);
       this.HasOptional(c => c.Spouse)
           .WithMany()
           .IsIndependent()
           .Map(m => m.MapKey(fk => fk.Id, "SpouseId"));
     }
}

MyObjectContext.cs

public class MyObjectContext : DbContext, IDbContext
{
  public DbSet<Contact> Contacts {get;set;}
  protected override void OnModelCreating(ModelBuilder modelBuilder)
     {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Configurations.Add(new ContactMap());
     }
}

Note: I also added the “[ForeignKey(“SpouseId”)]” attribute to my Spouse property in my Contact class. Unfortunately I keep getting “Sequence contains more than one matching element”.

EDIT2:
Morteza’s answers below is correct. To summarize: For self referencing foreign keys you can either mark the property as a “[ForeginKey(“SpouseId”)] OR use the fluent API example below. The errors I reported in some of my comments were caused by my unit test. EF generated the db the correct way. I found a good link where Craig Stuntz outlined why auto-increment keys and self-referencing foreign keys can cause the “Unable to determine a valid ordering for dependent operations” error. I believe this is what my problem is. Hope this helps someone.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-19T15:12:37+00:00Added an answer on May 19, 2026 at 3:12 pm

    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
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to drop a foreign key from a table referencing a specified
I'm trying to retrieve a user object from a foreign key reference but each
I'm trying to create a foreign key on a table in MySQL and I'm
How do I create a foreign key from table tGeoAnswers column 'locationId' to table
I'm getting a Can't use an undefined value as a HASH reference error trying
Trying the ggplot2 examples in the online reference manual, and particularly in this page
I'm having a problem with foreign key in mysql.I'm trying to insert a row
I am trying to fetch a row from a table in my database, and
I'm trying to create a foreign key in a SQL Compact database but I
I'm trying to add a table from my database to my LINQ to SQL

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.