I am not 100% sure which db scheme you are trying to achieve here. My guess is that you want to have a foreign key in the same table. In your comment, you said you want a one to one ship relationship. Technically, this is not possible. Because when you try to insert the first record, you need to specify a value for the foreign key column. The value must be the identifier of an existing record. Wait ... We have no entries yet!
Since 1-1 is not very practical here, you should do one to zero / one. This means that your foreign key column must be NULL so that you can insert the first record with a NULL value in the foreign key column.
Itβs a little difficult for me to understand your model names and properties. Therefore, I am going to use a common class / table that everyone can understand, but with your specific requirement (foreign key of an external link)
I do not use data annotations, I use the Fluent API
The stupid business requirement / assumption is this:
- A person may or may not have a Parent
- A person may or may not have a kid
So, our entity class will look like this
public class Person { public int Id { set; get; } public string Name { set; get; } public virtual Person Parent { set; get; } public virtual Person Kid { set; get; } }
Now, to use the free relationship management API, we need to go to our DBContext class and override the OnModelCreating method
public class MyDbContext : DbContext { public MyDbContext() : base("MyConnectionStringName") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Person>().HasKey(d => d.Id) .HasOptional(m => m.Kid).WithOptionalPrincipal(d=>d.Parent); base.OnModelCreating(modelBuilder); } public DbSet<Person> Persons { set; get; } }
This will create a table with three columns, ID , Name and Parent_Id (NULLABLE, Foreign Key to ID the same table ratio)
I can insert data like this
var db = new MyDbContext(); var myMom = new Person {Name = "Indira"}; var me = new Person {Name = "Shyju", Parent = myMom}; var myDaughter = new Person { Name = "Gauri", Parent = me}; db.Persons.Add(myMom); db.Persons.Add(me); db.Persons.Add(myDaughter); db.SaveChanges();
And you will have the data with the ParentId column with the foreign key in the ID column of the same table.
